Compare commits
336 changed files with 494 additions and 53605 deletions
|
|
@ -1 +0,0 @@
|
||||||
test_workspace = true
|
|
||||||
35
.github/workflows/portable-contracts.yml
vendored
35
.github/workflows/portable-contracts.yml
vendored
|
|
@ -8,11 +8,6 @@ on:
|
||||||
pull_request:
|
pull_request:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
concurrency:
|
|
||||||
# A newer push or PR update replaces the older run on the same ref; workflow_dispatch runs are never cancelled.
|
|
||||||
group: ${{ github.workflow }}-${{ github.ref }}
|
|
||||||
cancel-in-progress: ${{ github.event_name != 'workflow_dispatch' }}
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
contracts-and-browser:
|
contracts-and-browser:
|
||||||
name: ${{ matrix.os }} ${{ matrix.package }}
|
name: ${{ matrix.os }} ${{ matrix.package }}
|
||||||
|
|
@ -21,10 +16,7 @@ jobs:
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
# No Windows runner exists: the windows-latest leg runs on workflow_dispatch only (GitHub or a
|
os: [windows-latest, ubuntu-latest]
|
||||||
# Windows runner), the ubuntu-latest leg gates push and PR. Windows push/PR triggers return in the PR
|
|
||||||
# that registers a Windows runner.
|
|
||||||
os: ${{ fromJSON(github.event_name == 'workflow_dispatch' && '["windows-latest", "ubuntu-latest"]' || '["ubuntu-latest"]') }}
|
|
||||||
package: [eve-contracts, eve-browser-lowering]
|
package: [eve-contracts, eve-browser-lowering]
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
|
|
@ -38,14 +30,6 @@ jobs:
|
||||||
cache: npm
|
cache: npm
|
||||||
cache-dependency-path: packages/${{ matrix.package }}/package-lock.json
|
cache-dependency-path: packages/${{ matrix.package }}/package-lock.json
|
||||||
|
|
||||||
# eve-browser-lowering links eve-contracts as file:../eve-contracts; npm installs none of the
|
|
||||||
# linked package's dependencies, and tsc resolves its declarations from the real path, so
|
|
||||||
# ajv must be installed in eve-contracts itself.
|
|
||||||
- name: Install eve-contracts dependencies
|
|
||||||
if: matrix.package != 'eve-contracts'
|
|
||||||
working-directory: packages/eve-contracts
|
|
||||||
run: npm ci
|
|
||||||
|
|
||||||
- name: Install package dependencies
|
- name: Install package dependencies
|
||||||
working-directory: packages/${{ matrix.package }}
|
working-directory: packages/${{ matrix.package }}
|
||||||
run: npm ci
|
run: npm ci
|
||||||
|
|
@ -54,23 +38,6 @@ jobs:
|
||||||
working-directory: packages/${{ matrix.package }}
|
working-directory: packages/${{ matrix.package }}
|
||||||
run: npm test
|
run: npm test
|
||||||
|
|
||||||
# The forge runner images carry no pwsh; GitHub's Windows and hosted images do.
|
|
||||||
- name: Install PowerShell
|
|
||||||
if: runner.os == 'Linux'
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
if command -v pwsh >/dev/null; then pwsh -Version; exit 0; fi
|
|
||||||
SUDO=""; [ "$(id -u)" -eq 0 ] || SUDO="sudo"
|
|
||||||
PWSH_VERSION=7.4.6
|
|
||||||
curl -fsSL "https://github.com/PowerShell/PowerShell/releases/download/v${PWSH_VERSION}/powershell-${PWSH_VERSION}-linux-x64.tar.gz" -o "${RUNNER_TEMP:-/tmp}/powershell.tar.gz"
|
|
||||||
$SUDO mkdir -p /opt/microsoft/powershell/7
|
|
||||||
$SUDO tar -xzf "${RUNNER_TEMP:-/tmp}/powershell.tar.gz" -C /opt/microsoft/powershell/7
|
|
||||||
$SUDO chmod +x /opt/microsoft/powershell/7/pwsh
|
|
||||||
$SUDO ln -sf /opt/microsoft/powershell/7/pwsh /usr/local/bin/pwsh
|
|
||||||
echo "DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1" >> "$GITHUB_ENV"
|
|
||||||
DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 pwsh -Version
|
|
||||||
|
|
||||||
- name: Reject stale generated output
|
- name: Reject stale generated output
|
||||||
shell: pwsh
|
shell: pwsh
|
||||||
run: |
|
run: |
|
||||||
|
|
|
||||||
11
.gitignore
vendored
11
.gitignore
vendored
|
|
@ -8,19 +8,12 @@ packages/eve-browser-lowering/node_modules/
|
||||||
!packages/eve-contracts/**
|
!packages/eve-contracts/**
|
||||||
packages/eve-contracts/node_modules/
|
packages/eve-contracts/node_modules/
|
||||||
packages/eve-contracts/*.tgz
|
packages/eve-contracts/*.tgz
|
||||||
!packages/thing-contract/
|
|
||||||
!packages/thing-contract/**
|
|
||||||
packages/thing-contract/node_modules/
|
|
||||||
packages/thing-contract/dist/
|
|
||||||
packages/thing-contract/dist-test/
|
|
||||||
!packages/org.gamecult.eve.surface/
|
!packages/org.gamecult.eve.surface/
|
||||||
!packages/org.gamecult.eve.surface/**
|
!packages/org.gamecult.eve.surface/**
|
||||||
packages/org.gamecult.eve.surface/bin~/
|
packages/org.gamecult.eve.surface/bin~/
|
||||||
packages/org.gamecult.eve.surface/obj~/
|
packages/org.gamecult.eve.surface/obj~/
|
||||||
!packages/org.gamecult.eve.unity-uitoolkit/
|
!packages/org.gamecult.eve.unity-uitoolkit/
|
||||||
!packages/org.gamecult.eve.unity-uitoolkit/**
|
!packages/org.gamecult.eve.unity-uitoolkit/**
|
||||||
!packages/GameCult.Thing.Contract/
|
|
||||||
!packages/GameCult.Thing.Contract/**
|
|
||||||
obj/
|
obj/
|
||||||
artifacts/
|
artifacts/
|
||||||
tools/deps/
|
tools/deps/
|
||||||
|
|
@ -32,4 +25,6 @@ flutter/eve_parity/assets/repixelizer/
|
||||||
*.deb
|
*.deb
|
||||||
*.ipa
|
*.ipa
|
||||||
*.dSYM/
|
*.dSYM/
|
||||||
/target
|
.voidbot/birth/
|
||||||
|
.voidbot/logs/
|
||||||
|
.voidbot/state/*.msgpack
|
||||||
|
|
|
||||||
8
.voidbot/state/README.md
Normal file
8
.voidbot/state/README.md
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
# Repo Persona State
|
||||||
|
|
||||||
|
This folder stores birth and continuity state for `Eve`.
|
||||||
|
Do not treat these files as arbitrary editable projections. Persistent memory should cross typed operation boundaries.
|
||||||
|
|
||||||
|
`docs/eve-face.md` is the human-readable mission/memory surface for Eve's repo
|
||||||
|
Persona. Keep `.voidbot/state/eve.cc` as the typed authority, and keep the docs
|
||||||
|
surface aligned when Eve's durable mission changes.
|
||||||
BIN
.voidbot/state/eve.cc
Normal file
BIN
.voidbot/state/eve.cc
Normal file
Binary file not shown.
7
.voidbot/status/void-memory-maintenance.json
Normal file
7
.voidbot/status/void-memory-maintenance.json
Normal file
|
|
@ -0,0 +1,7 @@
|
||||||
|
{
|
||||||
|
"status": "starting",
|
||||||
|
"startedAt": "2026-07-08T06:38:39.965Z",
|
||||||
|
"stateFile": "E:\\Projects\\Eve\\.voidbot\\state\\eve.cc",
|
||||||
|
"launcher": "repo_face_heartbeat",
|
||||||
|
"reason": "repo_face_napping_with_short_term_memory"
|
||||||
|
}
|
||||||
4
.voidbot/voice/README.md
Normal file
4
.voidbot/voice/README.md
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
# Repo Persona Voice
|
||||||
|
|
||||||
|
This folder belongs to the Discord-facing Persona for `Eve`.
|
||||||
|
Discord roles address the Persona; VoidBot's webhook persona pipe is the mouth.
|
||||||
BIN
.voidbot/voice/eve.png
Normal file
BIN
.voidbot/voice/eve.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 5.1 KiB |
10
.voidbot/voice/identity.json
Normal file
10
.voidbot/voice/identity.json
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
{
|
||||||
|
"schemaVersion": "voidbot.repo_face_identity.v0",
|
||||||
|
"identityId": "eve",
|
||||||
|
"repoName": "Eve",
|
||||||
|
"displayName": "Eve",
|
||||||
|
"roleId": "1510848465243082874",
|
||||||
|
"avatarUrl": "https://raw.githubusercontent.com/GameCult/VoidBot/codex/voidbot-cultcache-replace-retry/assets/repo-faces/eve.png",
|
||||||
|
"repoPath": "E:\\Projects\\Eve",
|
||||||
|
"createdOrRefreshedAt": "2026-07-08T03:32:39.737Z"
|
||||||
|
}
|
||||||
1008
Cargo.lock
generated
1008
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
15
Cargo.toml
15
Cargo.toml
|
|
@ -1,15 +0,0 @@
|
||||||
[workspace]
|
|
||||||
members = ["crates/*"]
|
|
||||||
resolver = "2"
|
|
||||||
|
|
||||||
[workspace.dependencies]
|
|
||||||
anyhow = "1"
|
|
||||||
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "4c9af401ae33812d862dde4ff3131433fc73c7dc", package = "cultcache-rs" }
|
|
||||||
serde = { version = "1", features = ["derive"] }
|
|
||||||
rmp-serde = "1.3"
|
|
||||||
taffy = { version = "0.16", default-features = false, features = ["std", "taffy_tree", "flexbox", "grid", "block_layout", "content_size"] }
|
|
||||||
# The terminal text tables, pinned exactly: a width is a golden. unicode-width drops its cjk
|
|
||||||
# tables, so ambiguous width is narrow.
|
|
||||||
unicode-width = { version = "=0.2.3", default-features = false }
|
|
||||||
unicode-segmentation = "=1.13.3"
|
|
||||||
unicode-linebreak = "=0.1.5"
|
|
||||||
21
LICENSE
21
LICENSE
|
|
@ -1,21 +0,0 @@
|
||||||
MIT License
|
|
||||||
|
|
||||||
Copyright (c) 2026 GameCult
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
||||||
56
README.md
56
README.md
|
|
@ -1,41 +1,4 @@
|
||||||
# Thing
|
# Eve
|
||||||
|
|
||||||
This repository is Thing (the Eve display, control and sensor edge for GameCult
|
|
||||||
apps). Its present tree is Thing 1, kept running for live consumers until each
|
|
||||||
ports; Thing 2.0 is built here (`docs/thing2-target.md`). The Thing 1 renderer
|
|
||||||
repos are archived under their Eve names: EveUnity, EveFlutter, EveElectron,
|
|
||||||
EveTui, EvePlugins and EveConformance.
|
|
||||||
|
|
||||||
## Start Here
|
|
||||||
|
|
||||||
Value: services publish a surface once, as a typed retained document
|
|
||||||
(`gamecult.eve.surface.v1`), and every runtime lowers it locally. Providers keep
|
|
||||||
authority over state and commands; Eve owns projection, input capture and
|
|
||||||
timestamped sensor publication.
|
|
||||||
|
|
||||||
Problem: without a shared surface contract, each service hand-builds its own
|
|
||||||
dashboard and each renderer re-implements layout, binding and commands.
|
|
||||||
|
|
||||||
Live (Thing 1):
|
|
||||||
|
|
||||||
- `packages/org.gamecult.eve.surface`: renderer-neutral C# surface contract and
|
|
||||||
composition builders; tests in `tests/GameCult.Eve.Surface.Serialization.Tests`.
|
|
||||||
- `packages/eve-contracts`: TypeScript types and validators generated from
|
|
||||||
`schemas/` (`npm run generate`, `npm test`).
|
|
||||||
- `packages/eve-browser-lowering`: browser DOM/CSS lowering of surface documents
|
|
||||||
(`npm test`).
|
|
||||||
- `web/`: browser reference oracle (`web/index.html`, `web/eve-dsl.js`; tests
|
|
||||||
with `node --test web/eve-dsl.test.mjs`).
|
|
||||||
- `docs/surface-contract-v1.md`: the contract. `docs/repo-strategy.md`: repo
|
|
||||||
ownership. `docs/parity-testing-harness.md` with
|
|
||||||
`scripts/run-parity-harness.ps1`: parity runs.
|
|
||||||
- `android/` and `Sources/` (iOS Theos app, `make package`): native proof
|
|
||||||
clients; build steps under Build Shape below.
|
|
||||||
|
|
||||||
Planned (Thing 2.0, in progress): `crates/thing-contract` is the first Rust
|
|
||||||
piece. The layout solver, text, accessibility tree, closed render-command list
|
|
||||||
and thin backends described in `docs/thing2-target.md` and `docs/thing2-map.md`
|
|
||||||
are not built yet; `docs/thing-campaign.md` holds the rename plan.
|
|
||||||
|
|
||||||
CultMesh-based surface web, portable control layer, and timestamped sensor
|
CultMesh-based surface web, portable control layer, and timestamped sensor
|
||||||
edge.
|
edge.
|
||||||
|
|
@ -214,6 +177,7 @@ See `docs/eve-dsl-reactive-bindings.md` for the first Eve DSL and reactive
|
||||||
CultMesh binding contract.
|
CultMesh binding contract.
|
||||||
See `docs/eve-multiverse.md` for the Eve MultiVerse philosophy and missing API
|
See `docs/eve-multiverse.md` for the Eve MultiVerse philosophy and missing API
|
||||||
surface.
|
surface.
|
||||||
|
See `docs/eve-persona.md` for Eve's persistent mission memory.
|
||||||
|
|
||||||
## Browser Reference
|
## Browser Reference
|
||||||
|
|
||||||
|
|
@ -246,8 +210,11 @@ render:
|
||||||
|
|
||||||
## VoidBot CEF Stream
|
## VoidBot CEF Stream
|
||||||
|
|
||||||
The CEF relay that produced these frames is not in VoidBot's default branch, so
|
Start the Starfire relay from `E:\Projects\VoidBot`:
|
||||||
no relay command is documented here until one exists.
|
|
||||||
|
```powershell
|
||||||
|
npm run swarm:eve-cef-relay -- --width 1620 --height 2160 --scale 2 --port 8792
|
||||||
|
```
|
||||||
|
|
||||||
EveCanvas displays binary JPEG frames and returns touch events only when a
|
EveCanvas displays binary JPEG frames and returns touch events only when a
|
||||||
stream lowering is configured through `EVE_STREAM_URLS`. The native app no
|
stream lowering is configured through `EVE_STREAM_URLS`. The native app no
|
||||||
|
|
@ -255,11 +222,12 @@ longer guesses a Starfire relay address.
|
||||||
|
|
||||||
## Mimir Sensor Uplink
|
## Mimir Sensor Uplink
|
||||||
|
|
||||||
Run the receiver processes from a Mimir checkout (a sibling `..\Mimir` here):
|
Start Mimir with `config/mimir-runtime.raven-eve.example.json` or run the
|
||||||
|
receiver processes directly:
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
dotnet run --project ..\Mimir\src\Mimir.EveSensorReceiver\Mimir.EveSensorReceiver.csproj -- --port 8793 --path /eve/camera --source-id eve-camera --type video-frame
|
dotnet run --project E:\Projects\Mimir\src\Mimir.EveSensorReceiver\Mimir.EveSensorReceiver.csproj -- --port 8793 --path /eve/camera --source-id eve-camera --type video-frame
|
||||||
dotnet run --project ..\Mimir\src\Mimir.EveSensorReceiver\Mimir.EveSensorReceiver.csproj -- --port 8794 --path /eve/mic --source-id eve-mic --type audio-block
|
dotnet run --project E:\Projects\Mimir\src\Mimir.EveSensorReceiver\Mimir.EveSensorReceiver.csproj -- --port 8794 --path /eve/mic --source-id eve-mic --type audio-block
|
||||||
```
|
```
|
||||||
|
|
||||||
EveCanvas sends binary `mimir.eve_media_observation.v1` camera and microphone
|
EveCanvas sends binary `mimir.eve_media_observation.v1` camera and microphone
|
||||||
|
|
@ -273,7 +241,7 @@ guess receiver URLs.
|
||||||
Start the dashboard authority on Starfire:
|
Start the dashboard authority on Starfire:
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
dotnet run --project ..\Mimir\src\Mimir.EveDashboard\Mimir.EveDashboard.csproj -- --port 8795
|
dotnet run --project E:\Projects\Mimir\src\Mimir.EveDashboard\Mimir.EveDashboard.csproj -- --port 8795
|
||||||
```
|
```
|
||||||
|
|
||||||
EveCanvas connects to the Mimir dashboard WebSocket lowering for native retained
|
EveCanvas connects to the Mimir dashboard WebSocket lowering for native retained
|
||||||
|
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
[package]
|
|
||||||
name = "thing-contract"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
license = "MIT"
|
|
||||||
publish = false
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
anyhow = { workspace = true }
|
|
||||||
cultcache-rs = { workspace = true }
|
|
||||||
serde = { workspace = true }
|
|
||||||
serde_bytes = "0.11"
|
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
thing-testkit = { path = "../thing-testkit" }
|
|
||||||
rmp-serde = { workspace = true }
|
|
||||||
|
|
@ -1,39 +0,0 @@
|
||||||
//! An asset catalog: the images a provider's surfaces reference by catalog id and asset id.
|
|
||||||
|
|
||||||
use cultcache_rs::{CultSlots, DatabaseEntry};
|
|
||||||
|
|
||||||
use crate::domain::{Count, Segment, Version};
|
|
||||||
use crate::keys::{ProviderId, asset_catalog_key};
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct AssetEntry {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub id: String,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub media_type: String,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub uri: String,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub width: Count,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub height: Count,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
|
||||||
#[cultcache(type = "gamecult.thing.asset_catalog", schema = "gamecult.thing.asset_catalog.v1")]
|
|
||||||
pub struct AssetCatalog {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub provider_id: ProviderId,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub catalog_id: Segment,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub version: Version,
|
|
||||||
#[cultcache(key = 3, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.AssetEntry>")]
|
|
||||||
pub assets: Vec<AssetEntry>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AssetCatalog {
|
|
||||||
pub fn record_key(&self) -> String {
|
|
||||||
asset_catalog_key(&self.provider_id, &self.catalog_id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,132 +0,0 @@
|
||||||
//! Commands: what a surface declares, and the one envelope a consumer sends. The caller's
|
|
||||||
//! identity has no field here: the transport sets it.
|
|
||||||
|
|
||||||
use cultcache_rs::{CultSlots, CultUnion, DatabaseEntry};
|
|
||||||
|
|
||||||
use crate::domain::Version;
|
|
||||||
use crate::keys::{CommandId, NodeId, SchemaId, invocation_key};
|
|
||||||
use crate::source::ParamName;
|
|
||||||
|
|
||||||
/// A command a surface declares. A node may reference only a declared command.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct CommandDecl {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub id: CommandId,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub payload_schema: SchemaId,
|
|
||||||
/// The input nodes whose current values travel with an invocation.
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub captures: Vec<NodeId>,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub confirm: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct CommandIdRef {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub id: CommandId,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum CommandRef {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Id(CommandIdRef),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Param(ParamName),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A typed record of the declared `payload_schema`, as its MessagePack bytes.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
#[cultcache(type_name = "GameCult.Thing.Contract.RecordPayload")]
|
|
||||||
pub struct RecordPayload {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub schema: SchemaId,
|
|
||||||
#[cultcache(key = 1, bytes)]
|
|
||||||
pub bytes: Vec<u8>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct TextValue {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct NumberValue {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct BoolValue {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct ChoiceValue {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum InputValue {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Text(TextValue),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Number(NumberValue),
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Bool(BoolValue),
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
Choice(ChoiceValue),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct CapturedInput {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub node: NodeId,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub value: InputValue,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A consumer's request that a provider run a declared command. Its fields are public, so a
|
|
||||||
/// result's copy of `invocation_id` is a convenience and not provenance: core binds results
|
|
||||||
/// to the invocations it issued.
|
|
||||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
|
||||||
#[cultcache(type = "gamecult.thing.command_invocation", schema = "gamecult.thing.command_invocation.v1")]
|
|
||||||
pub struct CommandInvocation {
|
|
||||||
/// A UUID string, unique per invocation.
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub invocation_id: String,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub surface_key: String,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub surface_version: Version,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub command: CommandId,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub payload: RecordPayload,
|
|
||||||
#[cultcache(key = 5, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.CapturedInput>")]
|
|
||||||
pub captured: Vec<CapturedInput>,
|
|
||||||
#[cultcache(key = 6)]
|
|
||||||
pub client: String,
|
|
||||||
/// RFC 3339, UTC.
|
|
||||||
#[cultcache(key = 7)]
|
|
||||||
pub issued_at: String,
|
|
||||||
#[cultcache(key = 8)]
|
|
||||||
pub delegation: Option<String>,
|
|
||||||
/// The activating node's declared id in the resolved tree. For a node inside a Repeat it is
|
|
||||||
/// the template's id, never an instance id. A confirmed invocation names the node confirmed;
|
|
||||||
/// a resumed one carries the source and items of the invocation whose result carried the effect.
|
|
||||||
#[cultcache(key = 9)]
|
|
||||||
pub source: NodeId,
|
|
||||||
/// The key of each Repeat instance enclosing the source, outermost first; empty outside any Repeat.
|
|
||||||
#[cultcache(key = 10, type_name = "System.Collections.Immutable.ImmutableArray<System.String>")]
|
|
||||||
pub items: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CommandInvocation {
|
|
||||||
pub fn record_key(&self) -> String {
|
|
||||||
invocation_key(&self.invocation_id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,237 +0,0 @@
|
||||||
//! The value domains of the contract's numbers and local names. Each domain is one field
|
|
||||||
//! type, and `new` is its only door: constructors, struct literals and every serde
|
|
||||||
//! `Deserializer` reach a value through it, so a value out of domain cannot exist.
|
|
||||||
//!
|
|
||||||
//! Each type writes and reads exactly the leaf of its inner type (`Int32`, `Int64`,
|
|
||||||
//! `String`), so the bytes are the plain leaf's. The reference's unsigned leaves are absent
|
|
||||||
//! from the TypeScript and Python packages, which is why the bound is a checked type here
|
|
||||||
//! and a refusal golden there.
|
|
||||||
|
|
||||||
use std::fmt;
|
|
||||||
|
|
||||||
use cultcache_rs::CultTypeName;
|
|
||||||
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
|
|
||||||
|
|
||||||
/// A value was outside its domain. Names the domain and its bound, never the value.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub struct DomainError {
|
|
||||||
domain: &'static str,
|
|
||||||
bound: &'static str,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DomainError {
|
|
||||||
const fn new(domain: &'static str, bound: &'static str) -> Self {
|
|
||||||
Self { domain, bound }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The type that refused.
|
|
||||||
pub fn domain(&self) -> &'static str {
|
|
||||||
self.domain
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The bound that was not met.
|
|
||||||
pub fn bound(&self) -> &'static str {
|
|
||||||
self.bound
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for DomainError {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
write!(f, "{} must be {}", self.domain, self.bound)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::error::Error for DomainError {}
|
|
||||||
|
|
||||||
/// A result's position in its invocation's answers, counting from 1. `new` is the only door:
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use thing_contract::Seq;
|
|
||||||
/// assert!(Seq::new(1).is_ok());
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0423
|
|
||||||
/// use thing_contract::Seq;
|
|
||||||
/// let _ = Seq(0);
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0616
|
|
||||||
/// use thing_contract::Seq;
|
|
||||||
/// let mut seq = Seq::FIRST;
|
|
||||||
/// seq.0 = 0;
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0599
|
|
||||||
/// use thing_contract::Seq;
|
|
||||||
/// let _ = Seq::default();
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0277
|
|
||||||
/// use thing_contract::Seq;
|
|
||||||
/// let _ = Seq::from(0);
|
|
||||||
/// ```
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
|
||||||
pub struct Seq(i32);
|
|
||||||
|
|
||||||
impl CultTypeName for Seq {
|
|
||||||
fn cult_type_name() -> String {
|
|
||||||
"System.Int32".to_string()
|
|
||||||
}
|
|
||||||
const VALUE_TYPE: bool = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Seq {
|
|
||||||
pub const FIRST: Seq = Seq(1);
|
|
||||||
|
|
||||||
pub fn new(value: i32) -> Result<Self, DomainError> {
|
|
||||||
if value >= 1 { Ok(Self(value)) } else { Err(DomainError::new("Seq", "at least 1")) }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get(self) -> i32 {
|
|
||||||
self.0
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The following position; stays at `i32::MAX` rather than leaving the domain.
|
|
||||||
pub fn next(self) -> Seq {
|
|
||||||
Seq(self.0.saturating_add(1))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A document or source version, never negative. `new` is the only door:
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use thing_contract::Version;
|
|
||||||
/// assert!(Version::new(0).is_ok());
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0423
|
|
||||||
/// use thing_contract::Version;
|
|
||||||
/// let _ = Version(-1);
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0599
|
|
||||||
/// use thing_contract::Version;
|
|
||||||
/// let _ = Version::default();
|
|
||||||
/// ```
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
|
||||||
pub struct Version(i64);
|
|
||||||
|
|
||||||
impl CultTypeName for Version {
|
|
||||||
fn cult_type_name() -> String {
|
|
||||||
"System.Int64".to_string()
|
|
||||||
}
|
|
||||||
const VALUE_TYPE: bool = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Version {
|
|
||||||
pub fn new(value: i64) -> Result<Self, DomainError> {
|
|
||||||
if value >= 0 { Ok(Self(value)) } else { Err(DomainError::new("Version", "at least 0")) }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get(self) -> i64 {
|
|
||||||
self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A count, an extent or an index, never negative. `new` is the only door:
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use thing_contract::Count;
|
|
||||||
/// assert!(Count::new(0).is_ok());
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0423
|
|
||||||
/// use thing_contract::Count;
|
|
||||||
/// let _ = Count(-1);
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0277
|
|
||||||
/// use thing_contract::Count;
|
|
||||||
/// let _: Count = (-1).into();
|
|
||||||
/// ```
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
|
||||||
pub struct Count(i32);
|
|
||||||
|
|
||||||
impl Count {
|
|
||||||
pub fn new(value: i32) -> Result<Self, DomainError> {
|
|
||||||
if value >= 0 { Ok(Self(value)) } else { Err(DomainError::new("Count", "at least 0")) }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get(self) -> i32 {
|
|
||||||
self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A name the contract joins into a record key: non-empty, no `.`. `new` is the only door:
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use thing_contract::Segment;
|
|
||||||
/// assert!(Segment::new("main").is_ok());
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0423
|
|
||||||
/// use thing_contract::Segment;
|
|
||||||
/// let _ = Segment(String::from("a.b"));
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0277
|
|
||||||
/// use thing_contract::Segment;
|
|
||||||
/// let _: Segment = "a.b".into();
|
|
||||||
/// ```
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
|
||||||
pub struct Segment(String);
|
|
||||||
|
|
||||||
impl CultTypeName for Segment {
|
|
||||||
fn cult_type_name() -> String {
|
|
||||||
"System.String".to_string()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Segment {
|
|
||||||
pub fn new(value: impl Into<String>) -> Result<Self, DomainError> {
|
|
||||||
let value = value.into();
|
|
||||||
if value.is_empty() {
|
|
||||||
Err(DomainError::new("Segment", "non-empty"))
|
|
||||||
} else if value.contains('.') {
|
|
||||||
Err(DomainError::new("Segment", "free of '.'"))
|
|
||||||
} else {
|
|
||||||
Ok(Self(value))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn as_str(&self) -> &str {
|
|
||||||
&self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
macro_rules! leaf_serde {
|
|
||||||
($name:ident, $inner:ty, $serialize:ident) => {
|
|
||||||
impl Serialize for $name {
|
|
||||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
|
||||||
serializer.$serialize(self.0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'de> Deserialize<'de> for $name {
|
|
||||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
|
||||||
Self::new(<$inner>::deserialize(deserializer)?).map_err(de::Error::custom)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
leaf_serde!(Seq, i32, serialize_i32);
|
|
||||||
leaf_serde!(Version, i64, serialize_i64);
|
|
||||||
leaf_serde!(Count, i32, serialize_i32);
|
|
||||||
|
|
||||||
impl Serialize for Segment {
|
|
||||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
|
||||||
serializer.serialize_str(&self.0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'de> Deserialize<'de> for Segment {
|
|
||||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
|
||||||
Self::new(String::deserialize(deserializer)?).map_err(de::Error::custom)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,77 +0,0 @@
|
||||||
//! Identifier newtypes and the record key of each kind. No caller spells a key as a free string.
|
|
||||||
|
|
||||||
use cultcache_rs::CultTypeName;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use crate::domain::{Segment, Seq, Version};
|
|
||||||
|
|
||||||
macro_rules! id_type {
|
|
||||||
($(#[$doc:meta])* $name:ident) => {
|
|
||||||
$(#[$doc])*
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
|
||||||
#[serde(transparent)]
|
|
||||||
pub struct $name(String);
|
|
||||||
|
|
||||||
impl $name {
|
|
||||||
pub fn new(value: impl Into<String>) -> Self {
|
|
||||||
Self(value.into())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn as_str(&self) -> &str {
|
|
||||||
&self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CultTypeName for $name {
|
|
||||||
fn cult_type_name() -> String {
|
|
||||||
"System.String".to_string()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
id_type!(
|
|
||||||
/// A provider of surfaces and state.
|
|
||||||
ProviderId
|
|
||||||
);
|
|
||||||
id_type!(
|
|
||||||
/// The schema id of a CultCache entry type, for example `gamecult.thing.surface.v1`.
|
|
||||||
SchemaId
|
|
||||||
);
|
|
||||||
id_type!(
|
|
||||||
/// The record key of a state record.
|
|
||||||
RecordKey
|
|
||||||
);
|
|
||||||
id_type!(
|
|
||||||
/// A node id, unique within its document after composition expansion.
|
|
||||||
NodeId
|
|
||||||
);
|
|
||||||
id_type!(
|
|
||||||
/// A command declared by a surface.
|
|
||||||
CommandId
|
|
||||||
);
|
|
||||||
|
|
||||||
// Each key joins free-string provider or publisher ids (dotted, as the Verse names them)
|
|
||||||
// with typed trailing parts: a `Segment` holds no dot and a `Seq` or `Version` is digits. A
|
|
||||||
// key therefore splits at its last dot (surface, asset catalog, result) or last two
|
|
||||||
// (composition), so two different field sets never build one key.
|
|
||||||
|
|
||||||
pub(crate) fn surface_key(provider: &ProviderId, label: &Segment) -> String {
|
|
||||||
format!("thing:surface:{}.{}", provider.as_str(), label.as_str())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn composition_key(publisher: &str, name: &Segment, version: Version) -> String {
|
|
||||||
format!("thing:composition:{publisher}.{}.v{}", name.as_str(), version.get())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn invocation_key(invocation_id: &str) -> String {
|
|
||||||
format!("thing:invocation:{invocation_id}")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn result_key(invocation_id: &str, seq: Seq) -> String {
|
|
||||||
format!("thing:result:{invocation_id}.{}", seq.get())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn asset_catalog_key(provider: &ProviderId, catalog_id: &Segment) -> String {
|
|
||||||
format!("thing:asset_catalog:{}.{}", provider.as_str(), catalog_id.as_str())
|
|
||||||
}
|
|
||||||
|
|
@ -1,58 +0,0 @@
|
||||||
//! The `gamecult.thing.*` wire types and their bytes. This crate owns the contract: the
|
|
||||||
//! golden payloads it blesses are what every other language package and core are held to.
|
|
||||||
//!
|
|
||||||
//! Every kind is a CultCache `DatabaseEntry`; every closed set is a `CultUnion` written
|
|
||||||
//! `[armKey, [slots...]]`, the shape the C# reference reads and writes.
|
|
||||||
//!
|
|
||||||
//! Decoding is a door as well as the constructors: every kind keeps its public serde
|
|
||||||
//! `Deserialize` (CultCache's `DatabaseEntry` requires it). The domains therefore live in the
|
|
||||||
//! field types (`Seq`, `Version`, `Count`, `Segment`), whose `Deserialize` calls the same
|
|
||||||
//! `new` the constructors call, so no door skips a check.
|
|
||||||
//!
|
|
||||||
//! Stack hazard: `Node` nests without a bound of its own, and serde's `Deserialize` recurses
|
|
||||||
//! once per level, so a hostile payload nested deep enough overflows the stack of a caller that
|
|
||||||
//! decodes it directly. CultCache refuses such a payload on read and on write
|
|
||||||
//! (`cultcache_rs::check_payload_depth`, 256 containers); a caller that decodes bytes outside a
|
|
||||||
//! CultCache must run that check first.
|
|
||||||
|
|
||||||
mod asset;
|
|
||||||
mod command;
|
|
||||||
mod domain;
|
|
||||||
mod keys;
|
|
||||||
mod node;
|
|
||||||
mod result;
|
|
||||||
mod source;
|
|
||||||
mod style;
|
|
||||||
|
|
||||||
pub use asset::*;
|
|
||||||
pub use command::*;
|
|
||||||
pub use domain::{Count, DomainError, Segment, Seq, Version};
|
|
||||||
pub use keys::{CommandId, NodeId, ProviderId, RecordKey, SchemaId, asset_catalog_key};
|
|
||||||
pub use node::*;
|
|
||||||
pub use result::*;
|
|
||||||
pub use source::*;
|
|
||||||
pub use style::*;
|
|
||||||
|
|
||||||
pub use cultcache_rs::DatabaseEntry;
|
|
||||||
|
|
||||||
/// Whether `text` is an RFC 3339 UTC-or-offset date-time of the one shape a Thing timestamp is
|
|
||||||
/// written in (`YYYY-MM-DDThh:mm:ss`, an optional fraction, then `Z` or an offset). A timestamp a
|
|
||||||
/// provider publishes as text is shown as written only when this accepts it.
|
|
||||||
pub fn is_timestamp_text(text: &str) -> bool {
|
|
||||||
cultcache_rs::is_stored_at_stamp(text)
|
|
||||||
}
|
|
||||||
use cultcache_rs::{CultCache, CultCacheRegistry};
|
|
||||||
|
|
||||||
/// Registers the five kinds with a cache.
|
|
||||||
pub struct ThingContract;
|
|
||||||
|
|
||||||
impl CultCacheRegistry for ThingContract {
|
|
||||||
fn register_entries(&self, cache: &mut CultCache) -> anyhow::Result<()> {
|
|
||||||
cache.register_entry_type::<SurfaceDocument>()?;
|
|
||||||
cache.register_entry_type::<CompositionDocument>()?;
|
|
||||||
cache.register_entry_type::<CommandInvocation>()?;
|
|
||||||
cache.register_entry_type::<CommandResult>()?;
|
|
||||||
cache.register_entry_type::<AssetCatalog>()?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,478 +0,0 @@
|
||||||
//! Thing Script: the closed node union, the surface document that holds a tree of nodes, and the
|
|
||||||
//! composition document that names a reusable subtree. Arm keys are fixed: Slot (13) is the arm
|
|
||||||
//! added after the first twelve, and a decoder from before it refuses a record holding one
|
|
||||||
//! (CultCache's unknown-arm rule).
|
|
||||||
|
|
||||||
use cultcache_rs::{CultSlots, CultUnion, DatabaseEntry};
|
|
||||||
|
|
||||||
use crate::domain::{Count, Segment, Version};
|
|
||||||
use crate::command::{CommandDecl, CommandRef};
|
|
||||||
use crate::keys::{NodeId, ProviderId, composition_key, surface_key};
|
|
||||||
use crate::source::{Bind, BoolSource, CollectionSource, MemberPath, NumberSource, ParamName, TextSource};
|
|
||||||
use crate::style::{BoxStyle, Paint, Role};
|
|
||||||
|
|
||||||
/// What every node carries.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct NodeCommon {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub id: NodeId,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub visible: BoolSource,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub a11y_label: Option<TextSource>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
#[cultcache(type_name = "GameCult.Thing.Contract.Node")]
|
|
||||||
pub enum Node {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Box(BoxNode),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Text(TextNode),
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Image(ImageNode),
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
Button(ButtonNode),
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
Toggle(ToggleNode),
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
Slider(SliderNode),
|
|
||||||
#[cultcache(key = 6)]
|
|
||||||
TextInput(TextInputNode),
|
|
||||||
#[cultcache(key = 7)]
|
|
||||||
Select(SelectNode),
|
|
||||||
#[cultcache(key = 8)]
|
|
||||||
Repeat(RepeatNode),
|
|
||||||
#[cultcache(key = 9)]
|
|
||||||
Overlay(OverlayNode),
|
|
||||||
#[cultcache(key = 10)]
|
|
||||||
Plot(PlotNode),
|
|
||||||
#[cultcache(key = 11)]
|
|
||||||
Embed(EmbedNode),
|
|
||||||
#[cultcache(key = 12)]
|
|
||||||
Use(UseNode),
|
|
||||||
#[cultcache(key = 13)]
|
|
||||||
Slot(SlotNode),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct BoxNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub style: BoxStyle,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub paint: Paint,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub role: Role,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub children: Vec<Node>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct TextNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub content: TextSource,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub style_token: String,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub wrap: bool,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub max_lines: Option<Count>,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
pub selectable: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum ImageFit {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Contain,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Cover,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Fill,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
Unscaled,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An asset of a catalog, with the alternative text a reader without the picture needs.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct ImageNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub catalog: String,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub asset: String,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub fit: ImageFit,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub alt: TextSource,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct ButtonNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub content: Vec<Node>,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub on_activate: CommandRef,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub enabled: BoolSource,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct ToggleNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub checked: BoolSource,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub on_change: CommandRef,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct SliderNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub min: f64,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub max: f64,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub step: f64,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub value: NumberSource,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
pub commit: CommandRef,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum InputKind {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Text,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Number,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct TextInputNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub multiline: bool,
|
|
||||||
/// Named `input_kind` in every runtime (Rust `input_kind`, C# `InputKind`, TypeScript `inputKind`): a field
|
|
||||||
/// named `kind` collides with the union tag in TypeScript. The wire is the slot key, 2.
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub input_kind: InputKind,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub placeholder: TextSource,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub initial: TextSource,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
pub submit: CommandRef,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct SelectOption {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: String,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub label: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct LiteralOptions {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub options: Vec<SelectOption>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Options read from a collection: each item's value and label are members of the item.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct BoundOptions {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub collection: CollectionSource,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub value_member: MemberPath,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub label_member: MemberPath,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum OptionList {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Literal(LiteralOptions),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Bound(BoundOptions),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct SelectNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub options: OptionList,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub value: Bind,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub on_change: CommandRef,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The template is instantiated once per item of the collection, keyed by `key_member` of the item.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct RepeatNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub collection: CollectionSource,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub key_member: MemberPath,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub template: std::boxed::Box<Node>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct AnchorNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub node: NodeId,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum Anchor {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Viewport,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Node(AnchorNode),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct OverlayNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub anchor: Anchor,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub modal: bool,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub dismiss: CommandRef,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub children: Vec<Node>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum PlotMark {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Line,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Bar,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Area,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct PlotNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
/// A numeric list member of a record.
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub series: Bind,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub mark: PlotMark,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub x_min: Option<f64>,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub x_max: Option<f64>,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
pub y_min: Option<f64>,
|
|
||||||
#[cultcache(key = 6)]
|
|
||||||
pub y_max: Option<f64>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A leaf the host draws: `slot_kind` is a name the host declares it supports.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct EmbedNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub slot_kind: String,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub slot_id: String,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub width: f64,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub height: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct CompositionRef {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub publisher: String,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub name: Segment,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub version: Version,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CompositionRef {
|
|
||||||
/// The record key of the composition this names, from the one key function.
|
|
||||||
pub fn record_key(&self) -> String {
|
|
||||||
composition_key(&self.publisher, &self.name, self.version)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct UseNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub composition: CompositionRef,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub args: Vec<Arg>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where a composition body places the nodes passed for its Slot parameter `param`. Only a child
|
|
||||||
/// list of a composition body holds one, and resolve refuses it elsewhere. It carries no
|
|
||||||
/// `NodeCommon`: the argument's nodes, keeping their caller-scope ids, replace it.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct SlotNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub param: ParamName,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct Arg {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub name: String,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub value: ArgValue,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct TextArg {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct NumberArg {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct BoolArg {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct CollectionArg {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub source: CollectionSource,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct CommandArg {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub command: CommandRef,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct SlotArg {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub nodes: Vec<Node>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum ArgValue {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Text(TextArg),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Number(NumberArg),
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Bool(BoolArg),
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
Bind(Bind),
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
Collection(CollectionArg),
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
Command(CommandArg),
|
|
||||||
#[cultcache(key = 6)]
|
|
||||||
Slot(SlotArg),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum ParamKind {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Text,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Number,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Bool,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
Bind,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
Collection,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
Command,
|
|
||||||
#[cultcache(key = 6)]
|
|
||||||
Slot,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct ParamDecl {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub name: String,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub kind: ParamKind,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A provider's surface: a tree of nodes and the commands it declares. A change of structure
|
|
||||||
/// republishes the record with a higher `version`.
|
|
||||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
|
||||||
#[cultcache(type = "gamecult.thing.surface", schema = "gamecult.thing.surface.v1")]
|
|
||||||
pub struct SurfaceDocument {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub provider_id: ProviderId,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub label: Segment,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub version: Version,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub title: String,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub root: Node,
|
|
||||||
#[cultcache(key = 5, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.CommandDecl>")]
|
|
||||||
pub commands: Vec<CommandDecl>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl SurfaceDocument {
|
|
||||||
pub fn record_key(&self) -> String {
|
|
||||||
surface_key(&self.provider_id, &self.label)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A reusable subtree with typed parameters. Compositions never own commands.
|
|
||||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
|
||||||
#[cultcache(type = "gamecult.thing.composition", schema = "gamecult.thing.composition.v1")]
|
|
||||||
pub struct CompositionDocument {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub publisher: String,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub name: Segment,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub version: Version,
|
|
||||||
#[cultcache(key = 3, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.ParamDecl>")]
|
|
||||||
pub params: Vec<ParamDecl>,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub body: Node,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CompositionDocument {
|
|
||||||
pub fn record_key(&self) -> String {
|
|
||||||
composition_key(&self.publisher, &self.name, self.version)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,231 +0,0 @@
|
||||||
//! The answer to a command invocation. A `CommandResult` is built by its four constructors,
|
|
||||||
//! each of which copies the invocation's id, and is read through accessors. Decoding is the
|
|
||||||
//! other door and holds the same domain: `seq` is a `Seq`, refused below 1 whichever door
|
|
||||||
//! it enters by. No API takes a state as a string or converts a map.
|
|
||||||
|
|
||||||
use cultcache_rs::{CultSlots, CultUnion, DatabaseEntry};
|
|
||||||
|
|
||||||
use crate::command::{CommandInvocation, CommandRef};
|
|
||||||
use crate::domain::{Seq, Version};
|
|
||||||
use crate::keys::{NodeId, result_key};
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct PendingOutcome {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub message: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct CompletedOutcome {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub source_version: Option<Version>,
|
|
||||||
/// Whether the captured drafts of the invocation clear.
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub clear_drafts: bool,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub effect: Option<Effect>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct DeniedOutcome {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub reason: String,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub node: Option<NodeId>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct FailedOutcome {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub reason: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
#[cultcache(type_name = "GameCult.Thing.Contract.Outcome")]
|
|
||||||
pub enum Outcome {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Pending(PendingOutcome),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Completed(CompletedOutcome),
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Denied(DeniedOutcome),
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
Failed(FailedOutcome),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct OpenSurfaceEffect {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub key: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct OpenExternalEffect {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub url: String,
|
|
||||||
/// The command run when the external step returns.
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub resume: CommandRef,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum Effect {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
OpenSurface(OpenSurfaceEffect),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
OpenExternal(OpenExternalEffect),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A provider's answer to one invocation. `seq` counts from 1 per invocation. The copied
|
|
||||||
/// invocation id is a convenience: core binds a result to an invocation it issued.
|
|
||||||
///
|
|
||||||
/// The positive case, a result built by a constructor from the invocation it answers:
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use thing_contract::{CommandInvocation, CommandResult, Seq};
|
|
||||||
/// fn answer(invocation: &CommandInvocation) -> CommandResult {
|
|
||||||
/// CommandResult::failed(invocation, Seq::FIRST, "refused")
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// A struct literal does not compile, because the fields are private:
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0451
|
|
||||||
/// use thing_contract::{CommandResult, FailedOutcome, Outcome, Seq};
|
|
||||||
/// let _ = CommandResult {
|
|
||||||
/// invocation_id: String::new(),
|
|
||||||
/// seq: Seq::FIRST,
|
|
||||||
/// outcome: Outcome::Failed(FailedOutcome { reason: String::new() }),
|
|
||||||
/// };
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// Each field is read through its accessor:
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use thing_contract::{CommandInvocation, CommandResult, Seq};
|
|
||||||
/// fn read(invocation: &CommandInvocation) {
|
|
||||||
/// let result = CommandResult::failed(invocation, Seq::FIRST, "refused");
|
|
||||||
/// let _ = result.invocation_id();
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// and assigning it does not compile:
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0616
|
|
||||||
/// use thing_contract::{CommandInvocation, CommandResult, Seq};
|
|
||||||
/// fn tamper(invocation: &CommandInvocation) {
|
|
||||||
/// let mut result = CommandResult::failed(invocation, Seq::FIRST, "refused");
|
|
||||||
/// result.invocation_id = String::new();
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use thing_contract::{CommandInvocation, CommandResult, Seq};
|
|
||||||
/// fn read(invocation: &CommandInvocation) {
|
|
||||||
/// let result = CommandResult::failed(invocation, Seq::FIRST, "refused");
|
|
||||||
/// let _ = result.seq();
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0616
|
|
||||||
/// use thing_contract::{CommandInvocation, CommandResult, Seq};
|
|
||||||
/// fn tamper(invocation: &CommandInvocation) {
|
|
||||||
/// let mut result = CommandResult::failed(invocation, Seq::FIRST, "refused");
|
|
||||||
/// result.seq = Seq::FIRST.next();
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use thing_contract::{CommandInvocation, CommandResult, Seq};
|
|
||||||
/// fn read(invocation: &CommandInvocation) {
|
|
||||||
/// let result = CommandResult::failed(invocation, Seq::FIRST, "refused");
|
|
||||||
/// let _ = result.outcome();
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0616
|
|
||||||
/// use thing_contract::{CommandInvocation, CommandResult, FailedOutcome, Outcome, Seq};
|
|
||||||
/// fn tamper(invocation: &CommandInvocation) {
|
|
||||||
/// let mut result = CommandResult::failed(invocation, Seq::FIRST, "refused");
|
|
||||||
/// result.outcome = Outcome::Failed(FailedOutcome { reason: String::new() });
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// Nothing converts a map into a result:
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0277
|
|
||||||
/// use std::collections::BTreeMap;
|
|
||||||
/// use thing_contract::CommandResult;
|
|
||||||
/// let flat: BTreeMap<String, String> = BTreeMap::new();
|
|
||||||
/// let _ = CommandResult::from(flat);
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// Nor a string state:
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0277
|
|
||||||
/// use thing_contract::CommandResult;
|
|
||||||
/// let _ = CommandResult::from("completed");
|
|
||||||
/// ```
|
|
||||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
|
||||||
#[cultcache(type = "gamecult.thing.command_result", schema = "gamecult.thing.command_result.v1")]
|
|
||||||
pub struct CommandResult {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
invocation_id: String,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
seq: Seq,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
outcome: Outcome,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CommandResult {
|
|
||||||
fn answering(invocation: &CommandInvocation, seq: Seq, outcome: Outcome) -> Self {
|
|
||||||
Self { invocation_id: invocation.invocation_id.clone(), seq, outcome }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn pending(invocation: &CommandInvocation, seq: Seq, message: impl Into<String>) -> Self {
|
|
||||||
Self::answering(invocation, seq, Outcome::Pending(PendingOutcome { message: message.into() }))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn completed(
|
|
||||||
invocation: &CommandInvocation,
|
|
||||||
seq: Seq,
|
|
||||||
source_version: Option<Version>,
|
|
||||||
clear_drafts: bool,
|
|
||||||
effect: Option<Effect>,
|
|
||||||
) -> Self {
|
|
||||||
Self::answering(
|
|
||||||
invocation,
|
|
||||||
seq,
|
|
||||||
Outcome::Completed(CompletedOutcome { source_version, clear_drafts, effect }),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn denied(
|
|
||||||
invocation: &CommandInvocation,
|
|
||||||
seq: Seq,
|
|
||||||
reason: impl Into<String>,
|
|
||||||
node: Option<NodeId>,
|
|
||||||
) -> Self {
|
|
||||||
Self::answering(invocation, seq, Outcome::Denied(DeniedOutcome { reason: reason.into(), node }))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn failed(invocation: &CommandInvocation, seq: Seq, reason: impl Into<String>) -> Self {
|
|
||||||
Self::answering(invocation, seq, Outcome::Failed(FailedOutcome { reason: reason.into() }))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn invocation_id(&self) -> &str {
|
|
||||||
&self.invocation_id
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn seq(&self) -> Seq {
|
|
||||||
self.seq
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn outcome(&self) -> &Outcome {
|
|
||||||
&self.outcome
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn record_key(&self) -> String {
|
|
||||||
result_key(&self.invocation_id, self.seq)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,172 +0,0 @@
|
||||||
//! Where a value comes from: a literal, a binding to a state record, or a composition parameter.
|
|
||||||
//! A member path is a list of names and indices, never an expression.
|
|
||||||
|
|
||||||
use cultcache_rs::{CultSlots, CultUnion};
|
|
||||||
|
|
||||||
use crate::domain::Count;
|
|
||||||
use crate::keys::{ProviderId, RecordKey, SchemaId};
|
|
||||||
|
|
||||||
/// A composition parameter, named.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct ParamName {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct TextLiteral {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct NumberLiteral {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct BoolLiteral {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum TextSource {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Literal(TextLiteral),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Bound(Bind),
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Param(ParamName),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum NumberSource {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Literal(NumberLiteral),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Bound(Bind),
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Param(ParamName),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum BoolSource {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Literal(BoolLiteral),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Bound(Bind),
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Param(ParamName),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One member of a record, read through a path, optionally formatted.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct Bind {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub source: StateSource,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub member: MemberPath,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub format: Option<Format>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum StateSource {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Record(StateRef),
|
|
||||||
/// The current item inside a `Repeat` template.
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Item,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A state record. An absent provider is the publisher of the document. `schema` is the id the
|
|
||||||
/// provider's record type is registered under in its store: a provider's state type must have its
|
|
||||||
/// entry type equal to that schema id, because a store names a record's schema by its entry type.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct StateRef {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub provider: Option<ProviderId>,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub schema: SchemaId,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub key: RecordKey,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct MemberPath {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub steps: Vec<MemberStep>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum MemberStep {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Name(MemberName),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Index(MemberIndex),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct MemberName {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct MemberIndex {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub index: Count,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum Format {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Number(NumberFormat),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Duration,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Timestamp,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
Affix(AffixFormat),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct NumberFormat {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub precision: Count,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub percent: bool,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub unit: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct AffixFormat {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub prefix: String,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub suffix: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The records of one type, or a list member of one record.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum CollectionSource {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Records(RecordsSource),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Member(Bind),
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Param(ParamName),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct RecordsSource {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub provider: Option<ProviderId>,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub schema: SchemaId,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub key_prefix: String,
|
|
||||||
}
|
|
||||||
|
|
@ -1,241 +0,0 @@
|
||||||
//! Box layout and paint as plain data. The crate holds no layout engine: core maps `BoxStyle`
|
|
||||||
//! onto its solver.
|
|
||||||
|
|
||||||
use cultcache_rs::{CultSlots, CultUnion};
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct Scalar {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum Dimension {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Px(Scalar),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Percent(Scalar),
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Fr(Scalar),
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
Auto,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
Content,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct Size2 {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub width: Dimension,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub height: Dimension,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct Edges {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub top: Dimension,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub right: Dimension,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub bottom: Dimension,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub left: Dimension,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum Display {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Flex,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Grid,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Block,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum Direction {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Row,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Column,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
RowReverse,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
ColumnReverse,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum Wrap {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
NoWrap,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Wrap,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
WrapReverse,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum Position {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Relative,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Absolute,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum Overflow {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Visible,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Clip,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Scroll,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum ItemAlign {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Auto,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Start,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
End,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
Center,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
Stretch,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
Baseline,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum ContentAlign {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Auto,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Start,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
End,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
Center,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
Stretch,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
SpaceBetween,
|
|
||||||
#[cultcache(key = 6)]
|
|
||||||
SpaceAround,
|
|
||||||
#[cultcache(key = 7)]
|
|
||||||
SpaceEvenly,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The layout of a box. `gap` is the column gap in `width` and the row gap in `height`.
|
|
||||||
/// `grid_columns` and `grid_rows` are the grid tracks and are read only when `display` is Grid.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct BoxStyle {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub display: Display,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub direction: Direction,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub wrap: Wrap,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub gap: Size2,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub padding: Edges,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
pub margin: Edges,
|
|
||||||
#[cultcache(key = 6)]
|
|
||||||
pub size: Size2,
|
|
||||||
#[cultcache(key = 7)]
|
|
||||||
pub min_size: Size2,
|
|
||||||
#[cultcache(key = 8)]
|
|
||||||
pub max_size: Size2,
|
|
||||||
#[cultcache(key = 9)]
|
|
||||||
pub position: Position,
|
|
||||||
#[cultcache(key = 10)]
|
|
||||||
pub inset: Edges,
|
|
||||||
#[cultcache(key = 11)]
|
|
||||||
pub overflow: Overflow,
|
|
||||||
#[cultcache(key = 12)]
|
|
||||||
pub align_items: ItemAlign,
|
|
||||||
#[cultcache(key = 13)]
|
|
||||||
pub align_self: ItemAlign,
|
|
||||||
#[cultcache(key = 14)]
|
|
||||||
pub align_content: ContentAlign,
|
|
||||||
#[cultcache(key = 15)]
|
|
||||||
pub justify_content: ContentAlign,
|
|
||||||
#[cultcache(key = 16)]
|
|
||||||
pub grow: f64,
|
|
||||||
#[cultcache(key = 17)]
|
|
||||||
pub shrink: f64,
|
|
||||||
#[cultcache(key = 18)]
|
|
||||||
pub basis: Dimension,
|
|
||||||
#[cultcache(key = 19)]
|
|
||||||
pub grid_columns: Vec<Dimension>,
|
|
||||||
#[cultcache(key = 20)]
|
|
||||||
pub grid_rows: Vec<Dimension>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct ThemeToken {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct Rgba {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub r: u8,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub g: u8,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub b: u8,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub a: u8,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum ColorRef {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Token(ThemeToken),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Rgba(Rgba),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct Border {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub color: ColorRef,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub width: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct Paint {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub background: Option<ColorRef>,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub border: Option<Border>,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub radius: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The accessibility role of a box. The accessibility tree itself is core's.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum Role {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Group,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Region,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
List,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
ListItem,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
Heading,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
Dialog,
|
|
||||||
#[cultcache(key = 6)]
|
|
||||||
Toolbar,
|
|
||||||
}
|
|
||||||
|
|
@ -1,63 +0,0 @@
|
||||||
//! The catalog rows the five document kinds publish are the rows the C# package declares:
|
|
||||||
//! `tests/thing-contract-parity/catalog-members.tsv`, which NameSetTests (C#) and parity.test.ts
|
|
||||||
//! (TypeScript) are held to as well. Schema ids differ by writer, so the comparison is by group,
|
|
||||||
//! as `catalogGroups` in parity.test.ts makes it.
|
|
||||||
|
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
use cultcache_rs::{DatabaseEntry, SchemaCatalogMember, SingleFileMessagePackBackingStore};
|
|
||||||
use thing_contract::*;
|
|
||||||
|
|
||||||
fn tsv_groups() -> Vec<String> {
|
|
||||||
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/thing-contract-parity/catalog-members.tsv");
|
|
||||||
let text = std::fs::read_to_string(path).unwrap();
|
|
||||||
let mut groups: Vec<(String, Vec<String>)> = Vec::new();
|
|
||||||
for row in text.lines().filter(|line| !line.trim().is_empty()) {
|
|
||||||
let (schema, rest) = row.split_once('\t').unwrap();
|
|
||||||
match groups.iter_mut().find(|(id, _)| id == schema) {
|
|
||||||
Some((_, rows)) => rows.push(rest.to_string()),
|
|
||||||
None => groups.push((schema.to_string(), vec![rest.to_string()])),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sorted(groups.into_iter().map(|(_, rows)| rows.join("\n")).collect())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn group(members: &[SchemaCatalogMember]) -> String {
|
|
||||||
members.iter().map(|m| format!("{}\t{}\t{}", m.slot, m.member_name, m.type_name)).collect::<Vec<_>>().join("\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn sorted(mut groups: Vec<String>) -> Vec<String> {
|
|
||||||
groups.sort();
|
|
||||||
groups
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rows_equal_the_csharp_file() {
|
|
||||||
let mine = sorted(vec![
|
|
||||||
group(&SurfaceDocument::schema_members()),
|
|
||||||
group(&CompositionDocument::schema_members()),
|
|
||||||
group(&CommandInvocation::schema_members()),
|
|
||||||
group(&CommandResult::schema_members()),
|
|
||||||
group(&AssetCatalog::schema_members()),
|
|
||||||
]);
|
|
||||||
assert_eq!(mine, tsv_groups());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn every_committed_store_carries_the_rows() {
|
|
||||||
// Each runtime's committed store, this crate's own included, declares the C# catalog. The Rust
|
|
||||||
// reader does not compare member type names when it opens a store, so a drifted name in a
|
|
||||||
// store another runtime wrote fails here. A store is copied first: reading it creates a lock
|
|
||||||
// file beside it.
|
|
||||||
for file in ["written-by-rs.cc", "written-by-cs.cc", "written-by-ts.cc"] {
|
|
||||||
let committed = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/thing-contract-parity").join(file);
|
|
||||||
let work = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!("catalog-members-{file}"));
|
|
||||||
std::fs::create_dir_all(&work).unwrap();
|
|
||||||
let copy = work.join(file);
|
|
||||||
std::fs::copy(committed, ©).unwrap();
|
|
||||||
let catalog = SingleFileMessagePackBackingStore::new(©).pull_schema_catalog().unwrap();
|
|
||||||
let from_store = sorted(catalog.iter().map(|entry| group(&entry.members)).collect());
|
|
||||||
assert_eq!(from_store, tsv_groups(), "{file}");
|
|
||||||
let _ = std::fs::remove_dir_all(&work);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,63 +0,0 @@
|
||||||
//! The stores the other two runtimes wrote. `written-by-cs.cc` and `written-by-ts.cc` in
|
|
||||||
//! `tests/thing-contract-parity` are read here, never written: each opens to exactly the five
|
|
||||||
//! records, each re-encodes to its value golden, and each sits under the key the other runtimes
|
|
||||||
//! key it by. The file is copied first: reading a store creates a lock file beside it.
|
|
||||||
|
|
||||||
use std::fmt::Debug;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
use cultcache_rs::DatabaseEntry;
|
|
||||||
use thing_contract::*;
|
|
||||||
use thing_testkit::{golden, store};
|
|
||||||
|
|
||||||
fn parity_dir() -> PathBuf {
|
|
||||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/thing-contract-parity")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn goldens_dir() -> PathBuf {
|
|
||||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn scratch(purpose: &str, bytes: &[u8]) -> PathBuf {
|
|
||||||
static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
|
||||||
let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
|
||||||
let work = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!("foreign-{purpose}-{serial}"));
|
|
||||||
std::fs::create_dir_all(&work).unwrap();
|
|
||||||
let copy = work.join("store.cc");
|
|
||||||
std::fs::write(©, bytes).unwrap();
|
|
||||||
copy
|
|
||||||
}
|
|
||||||
|
|
||||||
fn assert_record<T: DatabaseEntry + Debug>(cache: &cultcache_rs::CultCache, key: &str, golden_name: &str) {
|
|
||||||
let records = cache.get_all_with_keys::<T>().unwrap();
|
|
||||||
assert_eq!(records.len(), 1, "{golden_name}: one record of the kind");
|
|
||||||
let (found, value) = &records[0];
|
|
||||||
assert_eq!(found, key, "{golden_name}: keyed as the other runtimes key it");
|
|
||||||
let expected = golden::read(&goldens_dir(), &format!("{golden_name}.bin"));
|
|
||||||
assert_eq!(rmp_serde::to_vec(value).unwrap(), expected, "{golden_name}: re-encodes to its golden");
|
|
||||||
}
|
|
||||||
|
|
||||||
fn assert_five_records(cache: &cultcache_rs::CultCache) {
|
|
||||||
assert_record::<SurfaceDocument>(cache, "thing:surface:provider.a.main", "surface-all-arms");
|
|
||||||
assert_record::<CompositionDocument>(cache, "thing:composition:provider.a.panel.v3", "composition-all-params");
|
|
||||||
assert_record::<CommandInvocation>(cache, "thing:invocation:3f2b8c1e-5d44-4a6b-9a07-1c2d3e4f5a6b", "invocation-all-inputs");
|
|
||||||
assert_record::<CommandResult>(cache, "thing:result:3f2b8c1e-5d44-4a6b-9a07-1c2d3e4f5a6b.1", "result-pending");
|
|
||||||
assert_record::<AssetCatalog>(cache, "thing:asset_catalog:provider.a.icons", "asset-catalog");
|
|
||||||
assert_eq!(cache.snapshot().len(), 5, "no record beyond the five");
|
|
||||||
}
|
|
||||||
|
|
||||||
fn open_foreign(file: &str) {
|
|
||||||
let copy = scratch("foreign", &std::fs::read(parity_dir().join(file)).unwrap());
|
|
||||||
assert_five_records(&store::open(©));
|
|
||||||
let _ = std::fs::remove_dir_all(copy.parent().unwrap());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_store_csharp_wrote_opens_to_five_records_that_re_encode_to_the_goldens() {
|
|
||||||
open_foreign("written-by-cs.cc");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_store_typescript_wrote_opens_to_five_records_that_re_encode_to_the_goldens() {
|
|
||||||
open_foreign("written-by-ts.cc");
|
|
||||||
}
|
|
||||||
|
|
@ -1,685 +0,0 @@
|
||||||
//! The goldens: payload bytes written by this crate and nobody else, then compared byte for
|
|
||||||
//! byte. The TypeScript and C# packages and core are held to these files; none of them writes
|
|
||||||
//! one. `THING_BLESS=1` rewrites them; any other run compares.
|
|
||||||
|
|
||||||
use std::collections::BTreeSet;
|
|
||||||
use std::fmt::Debug;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
use thing_testkit::{build::*, golden, store};
|
|
||||||
use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry};
|
|
||||||
use thing_contract::*;
|
|
||||||
|
|
||||||
fn goldens_dir() -> PathBuf {
|
|
||||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where the stores of all three runtimes live; this crate writes `written-by-rs.cc` there.
|
|
||||||
fn parity_dir() -> PathBuf {
|
|
||||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/thing-contract-parity")
|
|
||||||
}
|
|
||||||
|
|
||||||
// A value that must never appear in a refusal.
|
|
||||||
const CANARY: &str = "CANARY-7f3a91c2";
|
|
||||||
|
|
||||||
fn golden<T: DatabaseEntry + PartialEq + Debug>(name: &str, value: &T) -> String {
|
|
||||||
let produced = rmp_serde::to_vec(value).unwrap();
|
|
||||||
let committed = golden::check(&goldens_dir(), &format!("{name}.bin"), &produced);
|
|
||||||
let decoded: T = rmp_serde::from_slice(&committed).unwrap_or_else(|error| panic!("{name}: {error}"));
|
|
||||||
assert_eq!(&decoded, value, "{name}: the golden does not decode to the constructed value");
|
|
||||||
assert_eq!(rmp_serde::to_vec(&decoded).unwrap(), committed, "{name}: re-encoding changed the bytes");
|
|
||||||
name.to_string()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn bind_all_formats() -> Vec<Bind> {
|
|
||||||
let number = Format::Number(NumberFormat { precision: count(2), percent: true, unit: Some("ms".into()) });
|
|
||||||
let affix = Format::Affix(AffixFormat { prefix: "$".into(), suffix: "/s".into() });
|
|
||||||
let indexed = MemberPath {
|
|
||||||
steps: vec![
|
|
||||||
MemberStep::Name(MemberName { name: "items".into() }),
|
|
||||||
MemberStep::Index(MemberIndex { index: count(3) }),
|
|
||||||
],
|
|
||||||
};
|
|
||||||
vec![
|
|
||||||
record_bind(indexed, Some(number)),
|
|
||||||
record_bind(path(&["elapsed"]), Some(Format::Duration)),
|
|
||||||
record_bind(path(&["at"]), Some(Format::Timestamp)),
|
|
||||||
record_bind(path(&["price"]), Some(affix)),
|
|
||||||
record_bind(path(&["plain"]), None),
|
|
||||||
item_bind(path(&["name"])),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A surface using all 13 node arms, nested more than four deep, with every source arm.
|
|
||||||
fn full_surface() -> SurfaceDocument {
|
|
||||||
let binds = bind_all_formats();
|
|
||||||
let bound_text = TextSource::Bound(binds[3].clone());
|
|
||||||
let bound_bool = BoolSource::Bound(binds[4].clone());
|
|
||||||
let bound_number = NumberSource::Bound(binds[0].clone());
|
|
||||||
|
|
||||||
let mut painted = BoxNode {
|
|
||||||
common: NodeCommon {
|
|
||||||
id: nid("painted"),
|
|
||||||
visible: BoolSource::Param(param("show")),
|
|
||||||
a11y_label: Some(TextSource::Param(param("label"))),
|
|
||||||
},
|
|
||||||
style: style(),
|
|
||||||
paint: Paint {
|
|
||||||
background: Some(ColorRef::Token(ThemeToken { name: "surface.raised".into() })),
|
|
||||||
border: Some(Border { color: ColorRef::Rgba(Rgba { r: 1, g: 2, b: 3, a: 255 }), width: 1.5 }),
|
|
||||||
radius: 4.0,
|
|
||||||
},
|
|
||||||
role: Role::Region,
|
|
||||||
children: vec![],
|
|
||||||
};
|
|
||||||
painted.style.display = Display::Grid;
|
|
||||||
painted.style.grid_columns = vec![Dimension::Fr(Scalar { value: 1.0 }), px(120.0)];
|
|
||||||
painted.style.grid_rows = vec![Dimension::Content];
|
|
||||||
painted.style.position = Position::Absolute;
|
|
||||||
painted.style.overflow = Overflow::Scroll;
|
|
||||||
painted.style.direction = Direction::RowReverse;
|
|
||||||
painted.style.wrap = Wrap::WrapReverse;
|
|
||||||
painted.style.align_items = ItemAlign::Baseline;
|
|
||||||
painted.style.align_self = ItemAlign::Center;
|
|
||||||
painted.style.align_content = ContentAlign::SpaceAround;
|
|
||||||
painted.style.justify_content = ContentAlign::SpaceEvenly;
|
|
||||||
painted.children = vec![text("deep-text", "deep")];
|
|
||||||
|
|
||||||
let repeat = Node::Repeat(RepeatNode {
|
|
||||||
common: common("rows"),
|
|
||||||
collection: CollectionSource::Records(RecordsSource {
|
|
||||||
provider: None,
|
|
||||||
schema: SchemaId::new("gamecult.thing.test.v1"),
|
|
||||||
key_prefix: "row-".into(),
|
|
||||||
}),
|
|
||||||
key_member: path(&["id"]),
|
|
||||||
template: std::boxed::Box::new(Node::Text(TextNode {
|
|
||||||
common: common("row-name"),
|
|
||||||
content: TextSource::Bound(item_bind(path(&["name"]))),
|
|
||||||
style_token: "body".into(),
|
|
||||||
wrap: false,
|
|
||||||
max_lines: Some(count(2)),
|
|
||||||
selectable: true,
|
|
||||||
})),
|
|
||||||
});
|
|
||||||
|
|
||||||
let leaves = vec![
|
|
||||||
Node::Text(TextNode {
|
|
||||||
common: common("t-bound"),
|
|
||||||
content: bound_text,
|
|
||||||
style_token: "label".into(),
|
|
||||||
wrap: true,
|
|
||||||
max_lines: None,
|
|
||||||
selectable: false,
|
|
||||||
}),
|
|
||||||
Node::Image(ImageNode {
|
|
||||||
common: common("img"),
|
|
||||||
catalog: "icons".into(),
|
|
||||||
asset: "gear".into(),
|
|
||||||
fit: ImageFit::Cover,
|
|
||||||
alt: lit_text("a gear"),
|
|
||||||
}),
|
|
||||||
Node::Button(ButtonNode {
|
|
||||||
common: common("go"),
|
|
||||||
content: vec![text("go-label", "Go")],
|
|
||||||
on_activate: command("go"),
|
|
||||||
enabled: bound_bool.clone(),
|
|
||||||
}),
|
|
||||||
Node::Toggle(ToggleNode { common: common("flag"), checked: bound_bool, on_change: CommandRef::Param(param("toggle")) }),
|
|
||||||
Node::Slider(SliderNode {
|
|
||||||
common: common("level"),
|
|
||||||
min: 0.0,
|
|
||||||
max: 1.0,
|
|
||||||
step: 0.25,
|
|
||||||
value: bound_number,
|
|
||||||
commit: command("set-level"),
|
|
||||||
}),
|
|
||||||
Node::TextInput(TextInputNode {
|
|
||||||
common: common("name-input"),
|
|
||||||
multiline: true,
|
|
||||||
input_kind: InputKind::Number,
|
|
||||||
placeholder: lit_text("name"),
|
|
||||||
initial: TextSource::Param(param("initial")),
|
|
||||||
submit: command("rename"),
|
|
||||||
}),
|
|
||||||
Node::TextInput(TextInputNode {
|
|
||||||
common: common("title-input"),
|
|
||||||
multiline: false,
|
|
||||||
input_kind: InputKind::Text,
|
|
||||||
placeholder: lit_text("title"),
|
|
||||||
initial: TextSource::Param(param("initial")),
|
|
||||||
submit: command("retitle"),
|
|
||||||
}),
|
|
||||||
Node::Select(SelectNode {
|
|
||||||
common: common("pick"),
|
|
||||||
options: OptionList::Literal(LiteralOptions {
|
|
||||||
options: vec![SelectOption { value: "a".into(), label: "Alpha".into() }],
|
|
||||||
}),
|
|
||||||
value: binds[4].clone(),
|
|
||||||
on_change: command("pick"),
|
|
||||||
}),
|
|
||||||
Node::Select(SelectNode {
|
|
||||||
common: common("pick-bound"),
|
|
||||||
options: OptionList::Bound(BoundOptions {
|
|
||||||
collection: CollectionSource::Member(binds[0].clone()),
|
|
||||||
value_member: path(&["id"]),
|
|
||||||
label_member: path(&["name"]),
|
|
||||||
}),
|
|
||||||
value: binds[5].clone(),
|
|
||||||
on_change: command("pick"),
|
|
||||||
}),
|
|
||||||
repeat,
|
|
||||||
Node::Overlay(OverlayNode {
|
|
||||||
common: common("menu"),
|
|
||||||
anchor: Anchor::Node(AnchorNode { node: nid("go") }),
|
|
||||||
modal: false,
|
|
||||||
dismiss: command("close"),
|
|
||||||
children: vec![text("menu-item", "one")],
|
|
||||||
}),
|
|
||||||
Node::Overlay(OverlayNode {
|
|
||||||
common: common("dialog"),
|
|
||||||
anchor: Anchor::Viewport,
|
|
||||||
modal: true,
|
|
||||||
dismiss: command("close"),
|
|
||||||
children: vec![],
|
|
||||||
}),
|
|
||||||
Node::Plot(PlotNode {
|
|
||||||
common: common("trend"),
|
|
||||||
series: binds[1].clone(),
|
|
||||||
mark: PlotMark::Area,
|
|
||||||
x_min: Some(0.0),
|
|
||||||
x_max: None,
|
|
||||||
y_min: None,
|
|
||||||
y_max: Some(100.0),
|
|
||||||
}),
|
|
||||||
Node::Embed(EmbedNode {
|
|
||||||
common: common("viewport"),
|
|
||||||
slot_kind: "world.scene".into(),
|
|
||||||
slot_id: "main".into(),
|
|
||||||
width: 640.0,
|
|
||||||
height: 480.0,
|
|
||||||
}),
|
|
||||||
Node::Use(UseNode {
|
|
||||||
common: common("kv"),
|
|
||||||
composition: CompositionRef { publisher: "thing.std".into(), name: seg("key-value"), version: ver(1) },
|
|
||||||
args: vec![Arg { name: "key".into(), value: ArgValue::Text(TextArg { value: "k".into() }) }],
|
|
||||||
}),
|
|
||||||
];
|
|
||||||
|
|
||||||
let mut deep = boxed("d4", vec![Node::Box(painted)]);
|
|
||||||
for id in ["d3", "d2", "d1"] {
|
|
||||||
deep = boxed(id, vec![deep]);
|
|
||||||
}
|
|
||||||
let mut children = vec![deep];
|
|
||||||
children.extend(leaves);
|
|
||||||
for plot_choice in [
|
|
||||||
Node::Plot(PlotNode {
|
|
||||||
common: common("trend-line"),
|
|
||||||
series: binds[2].clone(),
|
|
||||||
mark: PlotMark::Line,
|
|
||||||
x_min: None,
|
|
||||||
x_max: None,
|
|
||||||
y_min: None,
|
|
||||||
y_max: None,
|
|
||||||
}),
|
|
||||||
Node::Plot(PlotNode {
|
|
||||||
common: common("trend-bar"),
|
|
||||||
series: binds[2].clone(),
|
|
||||||
mark: PlotMark::Bar,
|
|
||||||
x_min: None,
|
|
||||||
x_max: None,
|
|
||||||
y_min: None,
|
|
||||||
y_max: None,
|
|
||||||
}),
|
|
||||||
] {
|
|
||||||
children.push(plot_choice);
|
|
||||||
}
|
|
||||||
for (index, fit) in [ImageFit::Contain, ImageFit::Fill, ImageFit::Unscaled].into_iter().enumerate() {
|
|
||||||
children.push(Node::Image(ImageNode {
|
|
||||||
common: common(&format!("img-fit-{index}")),
|
|
||||||
catalog: "icons".into(),
|
|
||||||
asset: "gear".into(),
|
|
||||||
fit,
|
|
||||||
alt: lit_text(""),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
for (index, role) in [Role::List, Role::ListItem, Role::Heading, Role::Dialog, Role::Toolbar].into_iter().enumerate() {
|
|
||||||
let mut role_style = style();
|
|
||||||
if index == 0 {
|
|
||||||
role_style.direction = Direction::Row;
|
|
||||||
role_style.align_content = ContentAlign::Auto;
|
|
||||||
role_style.justify_content = ContentAlign::Stretch;
|
|
||||||
}
|
|
||||||
children.push(Node::Box(BoxNode {
|
|
||||||
common: common(&format!("role-{index}")),
|
|
||||||
style: role_style,
|
|
||||||
paint: plain_paint(),
|
|
||||||
role,
|
|
||||||
children: vec![],
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
let mut block = BoxNode {
|
|
||||||
common: common("block"),
|
|
||||||
style: style(),
|
|
||||||
paint: plain_paint(),
|
|
||||||
role: Role::Group,
|
|
||||||
children: vec![],
|
|
||||||
};
|
|
||||||
block.style.display = Display::Block;
|
|
||||||
block.style.direction = Direction::ColumnReverse;
|
|
||||||
block.style.wrap = Wrap::Wrap;
|
|
||||||
block.style.overflow = Overflow::Clip;
|
|
||||||
block.style.align_content = ContentAlign::Center;
|
|
||||||
block.style.justify_content = ContentAlign::End;
|
|
||||||
block.style.align_items = ItemAlign::End;
|
|
||||||
block.style.align_self = ItemAlign::Start;
|
|
||||||
block.style.basis = Dimension::Content;
|
|
||||||
children.push(Node::Box(block));
|
|
||||||
children.push(Node::Text(TextNode {
|
|
||||||
common: common("t-param"),
|
|
||||||
content: TextSource::Param(param("title")),
|
|
||||||
style_token: "title".into(),
|
|
||||||
wrap: true,
|
|
||||||
max_lines: None,
|
|
||||||
selectable: false,
|
|
||||||
}));
|
|
||||||
children.push(Node::Toggle(ToggleNode {
|
|
||||||
common: NodeCommon { id: nid("literal-number"), visible: BoolSource::Param(param("v")), a11y_label: None },
|
|
||||||
checked: lit_bool(false),
|
|
||||||
on_change: command("toggle"),
|
|
||||||
}));
|
|
||||||
children.push(Node::Slider(SliderNode {
|
|
||||||
common: common("slider-literal"),
|
|
||||||
min: -1.0,
|
|
||||||
max: 1.0,
|
|
||||||
step: 0.5,
|
|
||||||
value: lit_number(0.5),
|
|
||||||
commit: command("set-level"),
|
|
||||||
}));
|
|
||||||
children.push(Node::Slider(SliderNode {
|
|
||||||
common: common("slider-param"),
|
|
||||||
min: 0.0,
|
|
||||||
max: 10.0,
|
|
||||||
step: 1.0,
|
|
||||||
value: NumberSource::Param(param("n")),
|
|
||||||
commit: command("set-level"),
|
|
||||||
}));
|
|
||||||
children.push(Node::Repeat(RepeatNode {
|
|
||||||
common: common("rows-param"),
|
|
||||||
collection: CollectionSource::Param(param("rows")),
|
|
||||||
key_member: path(&["id"]),
|
|
||||||
template: std::boxed::Box::new(text("row-param", "r")),
|
|
||||||
}));
|
|
||||||
|
|
||||||
SurfaceDocument {
|
|
||||||
provider_id: ProviderId::new("provider.a"),
|
|
||||||
label: seg("main"),
|
|
||||||
version: ver(7),
|
|
||||||
title: "All arms".into(),
|
|
||||||
root: boxed("root", children),
|
|
||||||
commands: vec![
|
|
||||||
CommandDecl {
|
|
||||||
id: CommandId::new("go"),
|
|
||||||
payload_schema: SchemaId::new("gamecult.thing.test.go.v1"),
|
|
||||||
captures: vec![nid("name-input"), nid("level")],
|
|
||||||
confirm: Some("Go now?".into()),
|
|
||||||
},
|
|
||||||
CommandDecl {
|
|
||||||
id: CommandId::new("close"),
|
|
||||||
payload_schema: SchemaId::new("gamecult.thing.test.close.v1"),
|
|
||||||
captures: vec![],
|
|
||||||
confirm: None,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn full_composition() -> CompositionDocument {
|
|
||||||
let args = vec![
|
|
||||||
Arg { name: "text".into(), value: ArgValue::Text(TextArg { value: "t".into() }) },
|
|
||||||
Arg { name: "number".into(), value: ArgValue::Number(NumberArg { value: 2.5 }) },
|
|
||||||
Arg { name: "bool".into(), value: ArgValue::Bool(BoolArg { value: true }) },
|
|
||||||
Arg { name: "bind".into(), value: ArgValue::Bind(record_bind(path(&["x"]), None)) },
|
|
||||||
Arg {
|
|
||||||
name: "collection".into(),
|
|
||||||
value: ArgValue::Collection(CollectionArg { source: CollectionSource::Param(param("rows")) }),
|
|
||||||
},
|
|
||||||
Arg { name: "command".into(), value: ArgValue::Command(CommandArg { command: command("go") }) },
|
|
||||||
Arg {
|
|
||||||
name: "slot".into(),
|
|
||||||
value: ArgValue::Slot(SlotArg { nodes: vec![text("slot-text", "inside"), boxed("slot-box", vec![])] }),
|
|
||||||
},
|
|
||||||
];
|
|
||||||
let inner_use = Node::Use(UseNode {
|
|
||||||
common: common("inner"),
|
|
||||||
composition: CompositionRef { publisher: "thing.std".into(), name: seg("card"), version: ver(2) },
|
|
||||||
args,
|
|
||||||
});
|
|
||||||
CompositionDocument {
|
|
||||||
publisher: "provider.a".into(),
|
|
||||||
name: seg("panel"),
|
|
||||||
version: ver(3),
|
|
||||||
params: [
|
|
||||||
("title", ParamKind::Text),
|
|
||||||
("count", ParamKind::Number),
|
|
||||||
("on", ParamKind::Bool),
|
|
||||||
("source", ParamKind::Bind),
|
|
||||||
("rows", ParamKind::Collection),
|
|
||||||
("act", ParamKind::Command),
|
|
||||||
("body", ParamKind::Slot),
|
|
||||||
]
|
|
||||||
.into_iter()
|
|
||||||
.map(|(name, kind)| ParamDecl { name: name.into(), kind })
|
|
||||||
.collect(),
|
|
||||||
body: boxed(
|
|
||||||
"panel-root",
|
|
||||||
vec![text("panel-title", "t"), inner_use, Node::Slot(SlotNode { param: param("body") })],
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn results(invocation: &CommandInvocation) -> Vec<(&'static str, CommandResult)> {
|
|
||||||
vec![
|
|
||||||
("result-pending", CommandResult::pending(invocation, seq(1), "working")),
|
|
||||||
("result-completed", CommandResult::completed(invocation, seq(2), Some(ver(8)), true, None)),
|
|
||||||
(
|
|
||||||
"result-completed-open-surface",
|
|
||||||
CommandResult::completed(
|
|
||||||
invocation,
|
|
||||||
seq(3),
|
|
||||||
None,
|
|
||||||
false,
|
|
||||||
Some(Effect::OpenSurface(OpenSurfaceEffect { key: "thing:surface:provider.a.next".into() })),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"result-completed-open-external",
|
|
||||||
CommandResult::completed(
|
|
||||||
invocation,
|
|
||||||
seq(4),
|
|
||||||
Some(ver(9)),
|
|
||||||
true,
|
|
||||||
Some(Effect::OpenExternal(OpenExternalEffect {
|
|
||||||
url: "https://example.test/auth".into(),
|
|
||||||
resume: command("resume"),
|
|
||||||
})),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
("result-denied", CommandResult::denied(invocation, seq(5), "not yours", Some(nid("go")))),
|
|
||||||
("result-denied-no-node", CommandResult::denied(invocation, seq(6), "not allowed", None)),
|
|
||||||
("result-failed", CommandResult::failed(invocation, seq(7), "broke")),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn asset_catalog() -> AssetCatalog {
|
|
||||||
AssetCatalog {
|
|
||||||
provider_id: ProviderId::new("provider.a"),
|
|
||||||
catalog_id: seg("icons"),
|
|
||||||
version: ver(2),
|
|
||||||
assets: vec![
|
|
||||||
AssetEntry { id: "gear".into(), media_type: "image/png".into(), uri: "assets/gear.png".into(), width: count(32), height: count(32) },
|
|
||||||
AssetEntry { id: "bolt".into(), media_type: "image/svg+xml".into(), uri: "assets/bolt.svg".into(), width: count(0), height: count(0) },
|
|
||||||
],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A store with one record of each kind, written by cultcache-rs under a pinned clock.
|
|
||||||
fn write_store(path: &std::path::Path) {
|
|
||||||
let mut cache = store::create(path);
|
|
||||||
let surface = full_surface();
|
|
||||||
let composition = full_composition();
|
|
||||||
let invocation = invocation();
|
|
||||||
let result = CommandResult::pending(&invocation, seq(1), "working");
|
|
||||||
let catalog = asset_catalog();
|
|
||||||
store::put_pinned(&mut cache, &surface.record_key(), &surface);
|
|
||||||
store::put_pinned(&mut cache, &composition.record_key(), &composition);
|
|
||||||
store::put_pinned(&mut cache, &invocation.record_key(), &invocation);
|
|
||||||
store::put_pinned(&mut cache, &result.record_key(), &result);
|
|
||||||
store::put_pinned(&mut cache, &catalog.record_key(), &catalog);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn envelope<T: DatabaseEntry>(key: &str, payload: Vec<u8>) -> CultCacheEnvelope {
|
|
||||||
CultCacheEnvelope {
|
|
||||||
key: key.into(),
|
|
||||||
r#type: T::TYPE.into(),
|
|
||||||
payload,
|
|
||||||
stored_at: store::PINNED_CLOCK.into(),
|
|
||||||
schema_id: Some(T::TYPE.into()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn slot_arm_bytes() {
|
|
||||||
let slot = Node::Slot(SlotNode { param: param("body") });
|
|
||||||
let bytes = rmp_serde::to_vec(&slot).unwrap();
|
|
||||||
assert_eq!(bytes, [0x92, 0x0D, 0x91, 0x91, 0xA4, 0x62, 0x6F, 0x64, 0x79]);
|
|
||||||
assert_eq!(rmp_serde::from_slice::<Node>(&bytes).unwrap(), slot);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn goldens_match() {
|
|
||||||
let mut names = BTreeSet::new();
|
|
||||||
names.insert(golden("surface-all-arms", &full_surface()));
|
|
||||||
names.insert(golden("composition-all-params", &full_composition()));
|
|
||||||
let invocation = invocation();
|
|
||||||
names.insert(golden("invocation-all-inputs", &invocation));
|
|
||||||
for (name, result) in results(&invocation) {
|
|
||||||
names.insert(golden(name, &result));
|
|
||||||
}
|
|
||||||
names.insert(golden("asset-catalog", &asset_catalog()));
|
|
||||||
|
|
||||||
// The refusal and tolerance goldens are written by `refusal_payloads` below; a stale file
|
|
||||||
// that no case names is an orphan.
|
|
||||||
let refusals = refusal_payloads();
|
|
||||||
for (name, bytes) in &refusals {
|
|
||||||
golden::check(&goldens_dir(), &format!("{name}.bin"), bytes);
|
|
||||||
names.insert((*name).to_string());
|
|
||||||
}
|
|
||||||
let on_disk: BTreeSet<String> = std::fs::read_dir(goldens_dir())
|
|
||||||
.unwrap()
|
|
||||||
.filter_map(|entry| entry.unwrap().file_name().into_string().ok())
|
|
||||||
.filter_map(|file| file.strip_suffix(".bin").map(str::to_string))
|
|
||||||
.collect();
|
|
||||||
assert_eq!(on_disk, names, "every .bin golden is a named case and every case has its file");
|
|
||||||
|
|
||||||
// The store: one record of each kind, written under a pinned clock, byte for byte.
|
|
||||||
let scratch = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("goldens-surface.cc");
|
|
||||||
write_store(&scratch);
|
|
||||||
let parity = parity_dir();
|
|
||||||
let committed = golden::check(&parity, "written-by-rs.cc", &std::fs::read(&scratch).unwrap());
|
|
||||||
let reopened = parity.join("written-by-rs.cc");
|
|
||||||
assert_eq!(std::fs::read(&reopened).unwrap(), committed);
|
|
||||||
let cache = store::open(&scratch);
|
|
||||||
let surface = full_surface();
|
|
||||||
assert_eq!(cache.get::<SurfaceDocument>(&surface.record_key()).unwrap(), Some(surface));
|
|
||||||
let composition = full_composition();
|
|
||||||
assert_eq!(cache.get::<CompositionDocument>(&composition.record_key()).unwrap(), Some(composition));
|
|
||||||
assert_eq!(cache.get::<CommandInvocation>(&invocation.record_key()).unwrap(), Some(invocation.clone()));
|
|
||||||
let result = CommandResult::pending(&invocation, seq(1), "working");
|
|
||||||
assert_eq!(cache.get::<CommandResult>(&result.record_key()).unwrap(), Some(result));
|
|
||||||
let catalog = asset_catalog();
|
|
||||||
assert_eq!(cache.get::<AssetCatalog>(&catalog.record_key()).unwrap(), Some(catalog));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The foreign and malformed payloads. Each is the bytes a consumer might send; none is a
|
|
||||||
/// value of this crate, so each is spelled from MessagePack tuples and maps.
|
|
||||||
fn refusal_payloads() -> Vec<(&'static str, Vec<u8>)> {
|
|
||||||
// The map a Thing 1 provider writes for a command result: named members, a receipt
|
|
||||||
// inside, no positional slots.
|
|
||||||
#[derive(serde::Serialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
struct Receipt {
|
|
||||||
command_id: &'static str,
|
|
||||||
command: &'static str,
|
|
||||||
state: &'static str,
|
|
||||||
message: &'static str,
|
|
||||||
source_version: u64,
|
|
||||||
issued_at_utc: &'static str,
|
|
||||||
}
|
|
||||||
#[derive(serde::Serialize)]
|
|
||||||
struct Flat {
|
|
||||||
receipt: Receipt,
|
|
||||||
}
|
|
||||||
let flat = Flat {
|
|
||||||
receipt: Receipt {
|
|
||||||
command_id: "inv-1",
|
|
||||||
command: "go",
|
|
||||||
state: "completed",
|
|
||||||
message: CANARY,
|
|
||||||
source_version: 4,
|
|
||||||
issued_at_utc: "2026-01-01T00:00:00Z",
|
|
||||||
},
|
|
||||||
};
|
|
||||||
let unit: [u8; 0] = [];
|
|
||||||
let pending = Outcome::Pending(PendingOutcome { message: CANARY.into() });
|
|
||||||
let root = text("root", "x");
|
|
||||||
vec![
|
|
||||||
("result-thing1-flat", rmp_serde::to_vec_named(&flat).unwrap()),
|
|
||||||
// A surface whose root is an arm key the Node union does not declare: 14 is the first key
|
|
||||||
// Node does not declare (Slot is 13).
|
|
||||||
(
|
|
||||||
"node-unknown-arm",
|
|
||||||
rmp_serde::to_vec(&("provider.a", "main", 1i64, CANARY, (14i32, (CANARY,)), unit)).unwrap(),
|
|
||||||
),
|
|
||||||
// A result whose outcome is an arm key the Outcome union does not declare.
|
|
||||||
("outcome-unknown-arm", rmp_serde::to_vec(&("inv-1", 1i32, (4i32, (CANARY,)))).unwrap()),
|
|
||||||
// A result with a fourth slot past the last declared one.
|
|
||||||
(
|
|
||||||
"result-extra-slot",
|
|
||||||
rmp_serde::to_vec(&("inv-1", 1i32, (0i32, ("working",)), CANARY)).unwrap(),
|
|
||||||
),
|
|
||||||
// Each domain refusal is a tuple of real values with one slot out of domain.
|
|
||||||
// A result at seq 0.
|
|
||||||
("result-seq-zero", rmp_serde::to_vec(&("inv-1", 0i32, &pending)).unwrap()),
|
|
||||||
// A surface at version -1.
|
|
||||||
(
|
|
||||||
"surface-version-negative",
|
|
||||||
rmp_serde::to_vec(&("provider.a", "main", -1i64, CANARY, &root, unit)).unwrap(),
|
|
||||||
),
|
|
||||||
// A surface whose label holds a dot, so its key would be ambiguous.
|
|
||||||
(
|
|
||||||
"surface-label-dotted",
|
|
||||||
rmp_serde::to_vec(&("provider.a", "b.c", 1i64, CANARY, &root, unit)).unwrap(),
|
|
||||||
),
|
|
||||||
// An asset whose width is negative.
|
|
||||||
(
|
|
||||||
"asset-extent-negative",
|
|
||||||
rmp_serde::to_vec(&("provider.a", "icons", 1i64, [("gear", "image/png", CANARY, -5i32, 32i32)])).unwrap(),
|
|
||||||
),
|
|
||||||
// A colour channel past the u8 leaf.
|
|
||||||
("rgba-channel-out-of-range", rmp_serde::to_vec(&(256i32, 0i32, 0i32, 255i32)).unwrap()),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn refusal_cases() {
|
|
||||||
let payloads: std::collections::BTreeMap<_, _> = refusal_payloads().into_iter().collect();
|
|
||||||
let committed = |name: &str| golden::check(&goldens_dir(), &format!("{name}.bin"), &payloads[name]);
|
|
||||||
|
|
||||||
// Stored under their key, each is refused naming the kind and the key, never a value.
|
|
||||||
let cases: [(&str, &str, &str); 7] = [
|
|
||||||
("result-thing1-flat", "gamecult.thing.command_result", "thing:result:inv-1.1"),
|
|
||||||
("node-unknown-arm", "gamecult.thing.surface", "thing:surface:provider.a.main"),
|
|
||||||
("outcome-unknown-arm", "gamecult.thing.command_result", "thing:result:inv-1.1"),
|
|
||||||
("result-seq-zero", "gamecult.thing.command_result", "thing:result:inv-1.0"),
|
|
||||||
("surface-version-negative", "gamecult.thing.surface", "thing:surface:provider.a.main"),
|
|
||||||
("surface-label-dotted", "gamecult.thing.surface", "thing:surface:provider.a.b.c"),
|
|
||||||
("asset-extent-negative", "gamecult.thing.asset_catalog", "thing:asset_catalog:provider.a.icons"),
|
|
||||||
];
|
|
||||||
for (name, kind, key) in cases {
|
|
||||||
let mut cache = CultCache::new();
|
|
||||||
ThingContract.register_entries(&mut cache).unwrap();
|
|
||||||
let bytes = committed(name);
|
|
||||||
let error = match kind {
|
|
||||||
"gamecult.thing.surface" => {
|
|
||||||
cache.put_envelope::<SurfaceDocument>(envelope::<SurfaceDocument>(key, bytes)).unwrap_err()
|
|
||||||
}
|
|
||||||
"gamecult.thing.asset_catalog" => {
|
|
||||||
cache.put_envelope::<AssetCatalog>(envelope::<AssetCatalog>(key, bytes)).unwrap_err()
|
|
||||||
}
|
|
||||||
_ => cache.put_envelope::<CommandResult>(envelope::<CommandResult>(key, bytes)).unwrap_err(),
|
|
||||||
};
|
|
||||||
let message = format!("{error:#}");
|
|
||||||
assert!(message.contains(kind), "{name}: the error names the kind: {message}");
|
|
||||||
assert!(message.contains(key), "{name}: the error names the record key: {message}");
|
|
||||||
assert!(!message.contains(CANARY), "{name}: the error echoed a value: {message}");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Decoded directly, the refusal names the union and the arm key, and never the payload.
|
|
||||||
for (name, union, key) in [("node-unknown-arm", "Node", "14"), ("outcome-unknown-arm", "Outcome", "4")] {
|
|
||||||
let bytes = committed(name);
|
|
||||||
let message = if union == "Node" {
|
|
||||||
rmp_serde::from_slice::<SurfaceDocument>(&bytes).unwrap_err().to_string()
|
|
||||||
} else {
|
|
||||||
rmp_serde::from_slice::<CommandResult>(&bytes).unwrap_err().to_string()
|
|
||||||
};
|
|
||||||
assert!(message.contains(union) && message.contains(key), "{name}: {message}");
|
|
||||||
assert!(!message.contains(CANARY), "{name}: {message}");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Decoded directly, a domain refusal names the domain and never the payload.
|
|
||||||
for (name, domain) in [
|
|
||||||
("result-seq-zero", "Seq"),
|
|
||||||
("surface-version-negative", "Version"),
|
|
||||||
("surface-label-dotted", "Segment"),
|
|
||||||
("asset-extent-negative", "Count"),
|
|
||||||
] {
|
|
||||||
let bytes = committed(name);
|
|
||||||
let message = match name {
|
|
||||||
"result-seq-zero" => rmp_serde::from_slice::<CommandResult>(&bytes).unwrap_err().to_string(),
|
|
||||||
"asset-extent-negative" => rmp_serde::from_slice::<AssetCatalog>(&bytes).unwrap_err().to_string(),
|
|
||||||
_ => rmp_serde::from_slice::<SurfaceDocument>(&bytes).unwrap_err().to_string(),
|
|
||||||
};
|
|
||||||
assert!(message.contains(domain), "{name}: {message}");
|
|
||||||
assert!(!message.contains(CANARY), "{name}: {message}");
|
|
||||||
}
|
|
||||||
|
|
||||||
// The u8 leaf refuses a channel past 255 when decoded as an Rgba.
|
|
||||||
let rgba = rmp_serde::from_slice::<Rgba>(&committed("rgba-channel-out-of-range")).unwrap_err();
|
|
||||||
assert!(!rgba.to_string().contains(CANARY));
|
|
||||||
|
|
||||||
// An extra trailing slot is read (CultLib's extra-trailing-slots ruling: read, never written
|
|
||||||
// back). Whether a missing slot is refused is CultLib's rule, so no golden asserts it.
|
|
||||||
let mut answered = invocation();
|
|
||||||
answered.invocation_id = "inv-1".into();
|
|
||||||
let extra: CommandResult = rmp_serde::from_slice(&committed("result-extra-slot")).unwrap();
|
|
||||||
assert_eq!(extra, CommandResult::pending(&answered, seq(1), "working"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn deep_tree() {
|
|
||||||
// A 64-deep Box chain.
|
|
||||||
let mut chain = text("leaf", "bottom");
|
|
||||||
for depth in (0..64).rev() {
|
|
||||||
chain = boxed(&format!("deep-{depth}"), vec![chain]);
|
|
||||||
}
|
|
||||||
let deep = SurfaceDocument {
|
|
||||||
provider_id: ProviderId::new("provider.a"),
|
|
||||||
label: seg("deep"),
|
|
||||||
version: ver(1),
|
|
||||||
title: "deep".into(),
|
|
||||||
root: chain,
|
|
||||||
commands: vec![],
|
|
||||||
};
|
|
||||||
// A surface of 1,000 nodes: the root, 998 texts and one box.
|
|
||||||
let mut wide_children: Vec<Node> = (0..998).map(|index| text(&format!("t{index}"), "x")).collect();
|
|
||||||
wide_children.push(boxed("tail", vec![]));
|
|
||||||
let wide = SurfaceDocument {
|
|
||||||
provider_id: ProviderId::new("provider.a"),
|
|
||||||
label: seg("wide"),
|
|
||||||
version: ver(1),
|
|
||||||
title: "wide".into(),
|
|
||||||
root: boxed("root", wide_children),
|
|
||||||
commands: vec![],
|
|
||||||
};
|
|
||||||
|
|
||||||
let path = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("deep-tree.cc");
|
|
||||||
{
|
|
||||||
let mut cache = store::create(&path);
|
|
||||||
store::put_pinned(&mut cache, &deep.record_key(), &deep);
|
|
||||||
store::put_pinned(&mut cache, &wide.record_key(), &wide);
|
|
||||||
}
|
|
||||||
let cache = store::open(&path);
|
|
||||||
assert_eq!(cache.get::<SurfaceDocument>(&deep.record_key()).unwrap(), Some(deep));
|
|
||||||
assert_eq!(cache.get::<SurfaceDocument>(&wide.record_key()).unwrap(), Some(wide));
|
|
||||||
}
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
* -text
|
|
||||||
|
|
@ -1,47 +0,0 @@
|
||||||
# thing-contract goldens
|
|
||||||
|
|
||||||
Written only by `crates/thing-contract/tests/goldens.rs`, with `THING_BLESS=1` set on that test.
|
|
||||||
Every other run compares byte for byte. The TypeScript and C# packages and core decode these files
|
|
||||||
and are held to the answers below; none of them writes one.
|
|
||||||
|
|
||||||
Each `.bin` is the payload of one record: the positional slot array of its kind, as MessagePack.
|
|
||||||
A union value is `[armKey, [armSlots...]]`; a unit arm is `[key, []]`. An optional member is nil
|
|
||||||
when absent. Arm keys are fixed for v1.
|
|
||||||
|
|
||||||
## Values (decode to the constructed value, re-encode to the same bytes)
|
|
||||||
|
|
||||||
| File | Kind | Decodes to |
|
|
||||||
|---|---|---|
|
|
||||||
| `surface-all-arms.bin` | `gamecult.thing.surface.v1` | One surface with 13 of the 14 node arms (Box 0, Text 1, Image 2, Button 3, Toggle 4, Slider 5, TextInput 6 as both input kinds, Text 0 and Number 1, Select 7, Repeat 8, Overlay 9, Plot 10, Embed 11, Use 12; Slot 13 is in `composition-all-params`, a body being where a slot stands), a Box chain four levels deep, every text, number and bool source arm, every Format arm, both state sources, both member steps, every dimension and colour arm, and two declared commands |
|
|
||||||
| `composition-all-params.bin` | `gamecult.thing.composition.v1` | A composition with one parameter of each of the 7 kinds, whose body uses a composition with one argument of each of the 7 argument arms and places the body slot (Slot 13) last in its root's children |
|
|
||||||
| `invocation-all-inputs.bin` | `gamecult.thing.command_invocation.v1` | An invocation with a payload record of bin bytes and one captured input of each of the 4 input arms, source `go-button` and items `[outer, inner]` |
|
|
||||||
| `result-pending.bin` | `gamecult.thing.command_result.v1` | Outcome Pending, seq 1 |
|
|
||||||
| `result-completed.bin` | same | Outcome Completed with source version 8, drafts cleared, no effect |
|
|
||||||
| `result-completed-open-surface.bin` | same | Completed with no source version and the OpenSurface effect |
|
|
||||||
| `result-completed-open-external.bin` | same | Completed with the OpenExternal effect and a resume command |
|
|
||||||
| `result-denied.bin` | same | Denied naming a node |
|
|
||||||
| `result-denied-no-node.bin` | same | Denied with a nil node |
|
|
||||||
| `result-failed.bin` | same | Failed |
|
|
||||||
| `asset-catalog.bin` | `gamecult.thing.asset_catalog.v1` | Two assets |
|
|
||||||
|
|
||||||
## Refusals and tolerance
|
|
||||||
|
|
||||||
| File | Payload | Expected |
|
|
||||||
|---|---|---|
|
|
||||||
| `result-thing1-flat.bin` | a MessagePack map with named members, the shape a Thing 1 provider wrote for a command result | refused when stored as a command result; the error names the kind and the record key and never a value |
|
|
||||||
| `node-unknown-arm.bin` | a surface whose root node has arm key 14, which Node does not declare | refused; the error names the kind and the record key, and decoded directly it names the union Node and the key 14, and never a value |
|
|
||||||
| `outcome-unknown-arm.bin` | a result whose outcome has arm key 4, which Outcome does not declare | refused in the same way, naming the union Outcome and the key 4 |
|
|
||||||
| `result-extra-slot.bin` | a Pending result with a fourth slot past the last one declared | read: it decodes to the Pending result with seq 1 (CultLib's extra-trailing-slots ruling: read, never written back) |
|
|
||||||
| `result-seq-zero.bin` | a result whose seq slot is 0 | refused; the error names the kind and the record key, decoded directly it names Seq, and never a value |
|
|
||||||
| `surface-version-negative.bin` | a surface whose version slot is -1 | refused in the same way, naming Version |
|
|
||||||
| `surface-label-dotted.bin` | a surface whose label is `b.c` | refused in the same way, naming Segment: a label holds no dot, so a record key splits at its last dot |
|
|
||||||
| `asset-extent-negative.bin` | an asset catalog whose first asset has width -5 | refused in the same way, naming Count |
|
|
||||||
| `rgba-channel-out-of-range.bin` | the Rgba slot array `[256, 0, 0, 255]` | refused when decoded as an Rgba: a channel is a byte, 0 to 255 |
|
|
||||||
|
|
||||||
Domain refusals are the contract's rule, which the TypeScript and C# packages mirror: each is held to refuse these files, without the leaf set a Rust `u8` or a checked newtype has.
|
|
||||||
|
|
||||||
## The nil vector
|
|
||||||
|
|
||||||
`nil-positions.tsv` is written only by `crates/thing-contract/tests/nil_positions.rs` (`THING_BLESS=1`). For every element inside an array, at every depth, of each value golden above (the eleven `.bin` files from `surface-all-arms` to `asset-catalog`), the test replaces that element with nil (`0xC0`) and decodes the whole payload with the Rust decode door, `rmp_serde::from_slice` into the golden's kind. A row is `golden`, `path` (dotted array indices from the root, e.g. `3.0.1`), the element's byte `start` and `end` in the golden, and `ACCEPT` or `REFUSE`. An accepted variant re-encodes to the spliced bytes. Maps are not walked.
|
|
||||||
|
|
||||||
A slot is required exactly when its Rust type is not optional, so `REFUSE` rows are the required slots and `ACCEPT` rows the optional ones. The Rust decode door decides every row; the TypeScript and C# packages keep no list of required slots and are held to every row.
|
|
||||||
Binary file not shown.
|
|
@ -1 +0,0 @@
|
||||||
”ªprovider.a¥icons‘•¤gear©image/png¯CANARY-7f3a91c2û
|
|
||||||
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load diff
|
|
@ -1 +0,0 @@
|
||||||
–ªprovider.a¤main¯CANARY-7f3a91c2’‘¯CANARY-7f3a91c2<63>
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
“¥inv-1’‘¯CANARY-7f3a91c2
|
|
||||||
Binary file not shown.
Binary file not shown.
|
|
@ -1 +0,0 @@
|
||||||
“Ù$3f2b8c1e-5d44-4a6b-9a07-1c2d3e4f5a6b’“ÃÀ
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
“Ù$3f2b8c1e-5d44-4a6b-9a07-1c2d3e4f5a6b’’«not allowedÀ
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
“Ù$3f2b8c1e-5d44-4a6b-9a07-1c2d3e4f5a6b’’©not yours¢go
|
|
||||||
Binary file not shown.
|
|
@ -1 +0,0 @@
|
||||||
“Ù$3f2b8c1e-5d44-4a6b-9a07-1c2d3e4f5a6b’‘¥broke
|
|
||||||
Binary file not shown.
Binary file not shown.
|
|
@ -1 +0,0 @@
|
||||||
<EFBFBD>§receipt†©commandId¥inv-1§command¢go¥state©completed§message¯CANARY-7f3a91c2sourceVersion«issuedAtUtc´2026-01-01T00:00:00Z
|
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -1,132 +0,0 @@
|
||||||
//! The nil vector: for every element of every array of every value golden, the golden with that
|
|
||||||
//! element replaced by nil, and whether the Rust decode door accepts it. A slot is required
|
|
||||||
//! exactly when its Rust type is not optional, so the rows are the required-slot set; the C# and
|
|
||||||
//! TypeScript packages hold no list of their own and are held to every row.
|
|
||||||
//! `THING_BLESS=1` rewrites `goldens/nil-positions.tsv`; any other run compares.
|
|
||||||
|
|
||||||
use std::fmt::Debug;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
use serde::Serialize;
|
|
||||||
use serde::de::DeserializeOwned;
|
|
||||||
use thing_contract::*;
|
|
||||||
use thing_testkit::golden;
|
|
||||||
|
|
||||||
/// One MessagePack value's byte span; `kids` is set for arrays only (maps are never walked).
|
|
||||||
struct Span {
|
|
||||||
start: usize,
|
|
||||||
end: usize,
|
|
||||||
kids: Option<Vec<Span>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn be(bytes: &[u8], at: usize, width: usize) -> usize {
|
|
||||||
bytes[at..at + width].iter().fold(0, |acc, byte| acc << 8 | *byte as usize)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn collection(bytes: &[u8], start: usize, mut at: usize, count: usize, is_array: bool) -> Span {
|
|
||||||
let mut kids = Vec::new();
|
|
||||||
for _ in 0..count {
|
|
||||||
let kid = item(bytes, at);
|
|
||||||
at = kid.end;
|
|
||||||
kids.push(kid);
|
|
||||||
}
|
|
||||||
Span { start, end: at, kids: is_array.then_some(kids) }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn item(bytes: &[u8], at: usize) -> Span {
|
|
||||||
let tag = bytes[at];
|
|
||||||
let flat = |len: usize| Span { start: at, end: at + len, kids: None };
|
|
||||||
match tag {
|
|
||||||
0x00..=0x7f | 0xe0..=0xff | 0xc0 | 0xc2 | 0xc3 => flat(1),
|
|
||||||
0x80..=0x8f => collection(bytes, at, at + 1, (tag & 0x0f) as usize * 2, false),
|
|
||||||
0x90..=0x9f => collection(bytes, at, at + 1, (tag & 0x0f) as usize, true),
|
|
||||||
0xa0..=0xbf => flat(1 + (tag & 0x1f) as usize),
|
|
||||||
0xc4 | 0xd9 => flat(2 + be(bytes, at + 1, 1)),
|
|
||||||
0xc5 | 0xda => flat(3 + be(bytes, at + 1, 2)),
|
|
||||||
0xc6 | 0xdb => flat(5 + be(bytes, at + 1, 4)),
|
|
||||||
0xca => flat(5),
|
|
||||||
0xcb => flat(9),
|
|
||||||
0xcc | 0xd0 => flat(2),
|
|
||||||
0xcd | 0xd1 => flat(3),
|
|
||||||
0xce | 0xd2 => flat(5),
|
|
||||||
0xcf | 0xd3 => flat(9),
|
|
||||||
0xdc => collection(bytes, at, at + 3, be(bytes, at + 1, 2), true),
|
|
||||||
0xdd => collection(bytes, at, at + 5, be(bytes, at + 1, 4), true),
|
|
||||||
0xde => collection(bytes, at, at + 3, be(bytes, at + 1, 2) * 2, false),
|
|
||||||
0xdf => collection(bytes, at, at + 5, be(bytes, at + 1, 4) * 2, false),
|
|
||||||
0xd4 => flat(3),
|
|
||||||
0xd5 => flat(4),
|
|
||||||
0xd6 => flat(6),
|
|
||||||
0xd7 => flat(10),
|
|
||||||
0xd8 => flat(18),
|
|
||||||
0xc7 => flat(3 + be(bytes, at + 1, 1)),
|
|
||||||
0xc8 => flat(4 + be(bytes, at + 1, 2)),
|
|
||||||
0xc9 => flat(6 + be(bytes, at + 1, 4)),
|
|
||||||
_ => panic!("unsupported tag {tag:#x} at {at}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every element inside an array, at every depth, in walk order, with its dotted index path.
|
|
||||||
fn elements(span: &Span, prefix: &str, out: &mut Vec<(String, usize, usize)>) {
|
|
||||||
for (index, kid) in span.kids.iter().flatten().enumerate() {
|
|
||||||
let path = if prefix.is_empty() { index.to_string() } else { format!("{prefix}.{index}") };
|
|
||||||
out.push((path.clone(), kid.start, kid.end));
|
|
||||||
elements(kid, &path, out);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The rows of one golden: nil spliced over each element, decoded as `T`. An accepted variant
|
|
||||||
/// must re-encode to the spliced bytes.
|
|
||||||
fn rows<T: DeserializeOwned + Serialize + Debug>(file: &str, out: &mut String) -> (usize, usize) {
|
|
||||||
let bytes = golden::read(&goldens_dir(), &format!("{file}.bin"));
|
|
||||||
let mut found = Vec::new();
|
|
||||||
elements(&item(&bytes, 0), "", &mut found);
|
|
||||||
let (mut accepted, mut refused) = (0, 0);
|
|
||||||
for (path, start, end) in found {
|
|
||||||
let mut spliced = bytes[..start].to_vec();
|
|
||||||
spliced.push(0xc0);
|
|
||||||
spliced.extend_from_slice(&bytes[end..]);
|
|
||||||
let verdict = match rmp_serde::from_slice::<T>(&spliced) {
|
|
||||||
Ok(value) => {
|
|
||||||
assert_eq!(rmp_serde::to_vec(&value).unwrap(), spliced, "{file} {path}: an accepted nil must re-encode to the spliced bytes");
|
|
||||||
accepted += 1;
|
|
||||||
"ACCEPT"
|
|
||||||
}
|
|
||||||
Err(_) => {
|
|
||||||
refused += 1;
|
|
||||||
"REFUSE"
|
|
||||||
}
|
|
||||||
};
|
|
||||||
out.push_str(&format!("{file}\t{path}\t{start}\t{end}\t{verdict}\n"));
|
|
||||||
}
|
|
||||||
(accepted, refused)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn nil_positions_match() {
|
|
||||||
let mut table = String::new();
|
|
||||||
let mut totals = Vec::new();
|
|
||||||
totals.push(("surface-all-arms", rows::<SurfaceDocument>("surface-all-arms", &mut table)));
|
|
||||||
totals.push(("composition-all-params", rows::<CompositionDocument>("composition-all-params", &mut table)));
|
|
||||||
totals.push(("invocation-all-inputs", rows::<CommandInvocation>("invocation-all-inputs", &mut table)));
|
|
||||||
for file in [
|
|
||||||
"result-pending",
|
|
||||||
"result-completed",
|
|
||||||
"result-completed-open-surface",
|
|
||||||
"result-completed-open-external",
|
|
||||||
"result-denied",
|
|
||||||
"result-denied-no-node",
|
|
||||||
"result-failed",
|
|
||||||
] {
|
|
||||||
totals.push((file, rows::<CommandResult>(file, &mut table)));
|
|
||||||
}
|
|
||||||
totals.push(("asset-catalog", rows::<AssetCatalog>("asset-catalog", &mut table)));
|
|
||||||
for (file, (accepted, refused)) in &totals {
|
|
||||||
println!("NILTOTAL {file} accept={accepted} refuse={refused}");
|
|
||||||
}
|
|
||||||
golden::check(&goldens_dir(), "nil-positions.tsv", table.as_bytes());
|
|
||||||
}
|
|
||||||
|
|
||||||
fn goldens_dir() -> PathBuf {
|
|
||||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
|
|
||||||
}
|
|
||||||
|
|
@ -1,224 +0,0 @@
|
||||||
use thing_testkit::build::*;
|
|
||||||
use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry, decode_payload};
|
|
||||||
use serde::Deserialize;
|
|
||||||
use serde::de::IntoDeserializer;
|
|
||||||
use serde::de::value::{Error as ValueError, I32Deserializer, I64Deserializer, StringDeserializer};
|
|
||||||
use thing_contract::*;
|
|
||||||
|
|
||||||
const CANARY: &str = "CANARY-9d41c7e0";
|
|
||||||
|
|
||||||
fn other_invocation() -> CommandInvocation {
|
|
||||||
let mut other = invocation();
|
|
||||||
other.invocation_id = "an-invocation-no-constructor-can-guess".into();
|
|
||||||
other
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn result_copies_invocation_id() {
|
|
||||||
let invocation = other_invocation();
|
|
||||||
let built = [
|
|
||||||
CommandResult::pending(&invocation, seq(1), "m"),
|
|
||||||
CommandResult::completed(&invocation, seq(2), None, false, None),
|
|
||||||
CommandResult::denied(&invocation, seq(3), "r", None),
|
|
||||||
CommandResult::failed(&invocation, seq(4), "r"),
|
|
||||||
];
|
|
||||||
for (index, result) in built.iter().enumerate() {
|
|
||||||
assert_eq!(result.invocation_id(), "an-invocation-no-constructor-can-guess");
|
|
||||||
assert_eq!(result.seq().get(), index as i32 + 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn each_constructor_builds_its_outcome_arm() {
|
|
||||||
let invocation = other_invocation();
|
|
||||||
let node = Some(nid("go"));
|
|
||||||
assert!(matches!(
|
|
||||||
CommandResult::pending(&invocation, seq(1), "wait").outcome(),
|
|
||||||
Outcome::Pending(PendingOutcome { message }) if message == "wait"
|
|
||||||
));
|
|
||||||
let effect = Effect::OpenSurface(OpenSurfaceEffect { key: "k".into() });
|
|
||||||
assert!(matches!(
|
|
||||||
CommandResult::completed(&invocation, seq(1), Some(ver(5)), true, Some(effect.clone())).outcome(),
|
|
||||||
Outcome::Completed(CompletedOutcome { source_version: Some(v), clear_drafts: true, effect: Some(e) })
|
|
||||||
if v.get() == 5 && *e == effect
|
|
||||||
));
|
|
||||||
assert!(matches!(
|
|
||||||
CommandResult::completed(&invocation, seq(1), None, false, None).outcome(),
|
|
||||||
Outcome::Completed(CompletedOutcome { source_version: None, clear_drafts: false, effect: None })
|
|
||||||
));
|
|
||||||
assert!(matches!(
|
|
||||||
CommandResult::denied(&invocation, seq(1), "no", node.clone()).outcome(),
|
|
||||||
Outcome::Denied(DeniedOutcome { reason, node: n }) if reason == "no" && *n == node
|
|
||||||
));
|
|
||||||
assert!(matches!(
|
|
||||||
CommandResult::failed(&invocation, seq(1), "broke").outcome(),
|
|
||||||
Outcome::Failed(FailedOutcome { reason }) if reason == "broke"
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn surface(provider: &str, label: &str) -> SurfaceDocument {
|
|
||||||
SurfaceDocument {
|
|
||||||
provider_id: ProviderId::new(provider),
|
|
||||||
label: seg(label),
|
|
||||||
version: ver(1),
|
|
||||||
title: String::new(),
|
|
||||||
root: boxed("r", vec![]),
|
|
||||||
commands: vec![],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn composition(publisher: &str, name: &str, version: i64) -> CompositionDocument {
|
|
||||||
CompositionDocument {
|
|
||||||
publisher: publisher.into(),
|
|
||||||
name: seg(name),
|
|
||||||
version: ver(version),
|
|
||||||
params: vec![],
|
|
||||||
body: boxed("r", vec![]),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn catalog(provider: &str, id: &str) -> AssetCatalog {
|
|
||||||
AssetCatalog { provider_id: ProviderId::new(provider), catalog_id: seg(id), version: ver(1), assets: vec![] }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn record_keys_are_built_from_the_fields() {
|
|
||||||
let invocation = other_invocation();
|
|
||||||
assert_eq!(invocation.record_key(), "thing:invocation:an-invocation-no-constructor-can-guess");
|
|
||||||
assert_eq!(
|
|
||||||
CommandResult::failed(&invocation, seq(3), "r").record_key(),
|
|
||||||
"thing:result:an-invocation-no-constructor-can-guess.3"
|
|
||||||
);
|
|
||||||
assert_eq!(surface("p", "main").record_key(), "thing:surface:p.main");
|
|
||||||
assert_eq!(composition("pub", "card", 2).record_key(), "thing:composition:pub.card.v2");
|
|
||||||
assert_eq!(catalog("p", "icons").record_key(), "thing:asset_catalog:p.icons");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn record_keys_injective() {
|
|
||||||
// The pair the old keys collided on: a dotted provider with a plain label, and a plain
|
|
||||||
// provider with a dotted label. The second no longer exists.
|
|
||||||
assert_eq!(surface("a.b", "c").record_key(), "thing:surface:a.b.c");
|
|
||||||
assert!(Segment::new("b.c").is_err());
|
|
||||||
assert_ne!(surface("a", "c").record_key(), surface("a.b", "c").record_key());
|
|
||||||
assert_ne!(surface("a.b", "c").record_key(), surface("a", "bc").record_key());
|
|
||||||
|
|
||||||
// A composition splits at its last two dots: publisher, name, then the version.
|
|
||||||
assert_eq!(composition("a.b", "c", 1).record_key(), "thing:composition:a.b.c.v1");
|
|
||||||
assert_ne!(composition("a.b", "c", 1).record_key(), composition("a", "bc", 1).record_key());
|
|
||||||
assert_ne!(composition("a", "c", 1).record_key(), composition("a", "c", 11).record_key());
|
|
||||||
assert_ne!(composition("a", "c", 1).record_key(), composition("a", "c", 0).record_key());
|
|
||||||
|
|
||||||
// A catalog likewise, and under the asset_catalog prefix.
|
|
||||||
assert_eq!(catalog("a.b", "c").record_key(), "thing:asset_catalog:a.b.c");
|
|
||||||
assert_ne!(catalog("a.b", "c").record_key(), catalog("a", "bc").record_key());
|
|
||||||
|
|
||||||
// A result splits at its last dot, and the seq is digits.
|
|
||||||
let mut inv = invocation();
|
|
||||||
inv.invocation_id = "x.1".into();
|
|
||||||
let first = CommandResult::failed(&inv, seq(2), "r").record_key();
|
|
||||||
inv.invocation_id = "x".into();
|
|
||||||
let second = CommandResult::failed(&inv, seq(12), "r").record_key();
|
|
||||||
assert_eq!(first, "thing:result:x.1.2");
|
|
||||||
assert_eq!(second, "thing:result:x.12");
|
|
||||||
assert_ne!(first, second);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn domain_newtypes_refuse_out_of_domain() {
|
|
||||||
// new, the one door.
|
|
||||||
for bad in [0, -1, i32::MIN] {
|
|
||||||
assert!(Seq::new(bad).is_err(), "Seq {bad}");
|
|
||||||
}
|
|
||||||
assert_eq!(Seq::new(1).unwrap(), Seq::FIRST);
|
|
||||||
assert_eq!(Seq::new(i32::MAX).unwrap().next(), Seq::new(i32::MAX).unwrap());
|
|
||||||
assert_eq!(Seq::FIRST.next().get(), 2);
|
|
||||||
assert!(Version::new(-1).is_err());
|
|
||||||
assert!(Version::new(i64::MIN).is_err());
|
|
||||||
assert_eq!(Version::new(0).unwrap().get(), 0);
|
|
||||||
assert!(Count::new(-1).is_err());
|
|
||||||
assert!(Count::new(i32::MIN).is_err());
|
|
||||||
assert_eq!(Count::new(0).unwrap().get(), 0);
|
|
||||||
assert_eq!(Count::new(7).unwrap().get(), 7);
|
|
||||||
assert!(Segment::new("").is_err());
|
|
||||||
assert!(Segment::new("a.b").is_err());
|
|
||||||
assert!(Segment::new(".").is_err());
|
|
||||||
assert_eq!(Segment::new("ab").unwrap().as_str(), "ab");
|
|
||||||
|
|
||||||
// serde, the other door: rmp_serde and serde's own IntoDeserializer.
|
|
||||||
for bad in [0, -1, i32::MIN] {
|
|
||||||
assert!(rmp_serde::from_slice::<Seq>(&rmp_serde::to_vec(&bad).unwrap()).is_err(), "Seq {bad}");
|
|
||||||
assert!(Seq::deserialize(I32Deserializer::<ValueError>::new(bad)).is_err());
|
|
||||||
assert!(Count::deserialize(I32Deserializer::<ValueError>::new(bad)).is_ok() == (bad >= 0));
|
|
||||||
}
|
|
||||||
assert_eq!(Seq::deserialize(I32Deserializer::<ValueError>::new(1)).unwrap(), Seq::FIRST);
|
|
||||||
assert!(rmp_serde::from_slice::<Version>(&rmp_serde::to_vec(&-1i64).unwrap()).is_err());
|
|
||||||
assert!(Version::deserialize(I64Deserializer::<ValueError>::new(-1)).is_err());
|
|
||||||
assert_eq!(Version::deserialize(I64Deserializer::<ValueError>::new(0)).unwrap().get(), 0);
|
|
||||||
assert!(rmp_serde::from_slice::<Count>(&rmp_serde::to_vec(&-1i32).unwrap()).is_err());
|
|
||||||
assert_eq!(Count::deserialize(I32Deserializer::<ValueError>::new(0)).unwrap().get(), 0);
|
|
||||||
for bad in ["", "a.b"] {
|
|
||||||
assert!(rmp_serde::from_slice::<Segment>(&rmp_serde::to_vec(bad).unwrap()).is_err(), "Segment {bad:?}");
|
|
||||||
let deserializer: StringDeserializer<ValueError> = bad.to_string().into_deserializer();
|
|
||||||
assert!(Segment::deserialize(deserializer).is_err());
|
|
||||||
}
|
|
||||||
let deserializer: StringDeserializer<ValueError> = "ab".to_string().into_deserializer();
|
|
||||||
assert_eq!(Segment::deserialize(deserializer).unwrap().as_str(), "ab");
|
|
||||||
|
|
||||||
// Each writes exactly the plain leaf, so the bytes are the leaf's.
|
|
||||||
assert_eq!(rmp_serde::to_vec(&seq(5)).unwrap(), rmp_serde::to_vec(&5i32).unwrap());
|
|
||||||
assert_eq!(rmp_serde::to_vec(&ver(5)).unwrap(), rmp_serde::to_vec(&5i64).unwrap());
|
|
||||||
assert_eq!(rmp_serde::to_vec(&count(5)).unwrap(), rmp_serde::to_vec(&5i32).unwrap());
|
|
||||||
assert_eq!(rmp_serde::to_vec(&seg("ab")).unwrap(), rmp_serde::to_vec("ab").unwrap());
|
|
||||||
|
|
||||||
// The error names the domain and its bound, never the value.
|
|
||||||
let message = Segment::new(format!("{CANARY}.x")).unwrap_err().to_string();
|
|
||||||
assert_eq!(message, "Segment must be free of '.'");
|
|
||||||
assert_eq!(Seq::new(-77).unwrap_err().to_string(), "Seq must be at least 1");
|
|
||||||
assert_eq!(Version::new(-77).unwrap_err().to_string(), "Version must be at least 0");
|
|
||||||
assert_eq!(Count::new(-77).unwrap_err().to_string(), "Count must be at least 0");
|
|
||||||
assert_eq!(Segment::new("").unwrap_err().to_string(), "Segment must be non-empty");
|
|
||||||
let error = Segment::new(format!("{CANARY}.x")).unwrap_err();
|
|
||||||
assert_eq!((error.domain(), error.bound()), ("Segment", "free of '.'"));
|
|
||||||
assert!(!format!("{error:?}").contains(CANARY));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The result payload `[id, seq, [0, [message]]]` with the seq slot spelled by the caller.
|
|
||||||
fn result_payload(seq_slot: i32) -> Vec<u8> {
|
|
||||||
let pending = Outcome::Pending(PendingOutcome { message: CANARY.into() });
|
|
||||||
rmp_serde::to_vec(&("inv-1", seq_slot, &pending)).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn result_decode_door_holds_domain() {
|
|
||||||
// A seq the constructors cannot build is refused by every decode door.
|
|
||||||
for bad in [0, -1, i32::MIN] {
|
|
||||||
let payload = result_payload(bad);
|
|
||||||
let message = rmp_serde::from_slice::<CommandResult>(&payload).unwrap_err().to_string();
|
|
||||||
assert!(message.contains("Seq") && !message.contains(CANARY), "{message}");
|
|
||||||
|
|
||||||
let message = format!("{:#}", decode_payload::<CommandResult>(&payload).unwrap_err());
|
|
||||||
assert!(!message.contains(CANARY), "{message}");
|
|
||||||
|
|
||||||
let mut cache = CultCache::new();
|
|
||||||
ThingContract.register_entries(&mut cache).unwrap();
|
|
||||||
let key = format!("thing:result:inv-1.{bad}");
|
|
||||||
let envelope = CultCacheEnvelope {
|
|
||||||
key: key.clone(),
|
|
||||||
r#type: CommandResult::TYPE.into(),
|
|
||||||
payload,
|
|
||||||
stored_at: "2026-01-01T00:00:00Z".into(),
|
|
||||||
schema_id: Some(CommandResult::TYPE.into()),
|
|
||||||
};
|
|
||||||
let message = format!("{:#}", cache.put_envelope::<CommandResult>(envelope).unwrap_err());
|
|
||||||
assert!(message.contains("gamecult.thing.command_result") && message.contains(&key), "{message}");
|
|
||||||
assert!(!message.contains(CANARY), "{message}");
|
|
||||||
}
|
|
||||||
|
|
||||||
// The boundary decodes, and equals what the constructor builds.
|
|
||||||
let mut answered = invocation();
|
|
||||||
answered.invocation_id = "inv-1".into();
|
|
||||||
let expected = CommandResult::pending(&answered, Seq::FIRST, CANARY);
|
|
||||||
assert_eq!(rmp_serde::from_slice::<CommandResult>(&result_payload(1)).unwrap(), expected);
|
|
||||||
assert_eq!(decode_payload::<CommandResult>(&result_payload(1)).unwrap(), expected);
|
|
||||||
}
|
|
||||||
|
|
@ -1,20 +0,0 @@
|
||||||
[package]
|
|
||||||
name = "thing-core"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
license = "MIT"
|
|
||||||
publish = false
|
|
||||||
|
|
||||||
# Normal dependencies are thing-contract, stacker, taffy and the three Unicode tables of the Cells
|
|
||||||
# text engine (unicode-width, unicode-segmentation, unicode-linebreak): layout and terminal text
|
|
||||||
# are thing-core's job, and no Taffy type is in its public API.
|
|
||||||
[dependencies]
|
|
||||||
thing-contract = { path = "../thing-contract" }
|
|
||||||
stacker = "0.1.25"
|
|
||||||
taffy.workspace = true
|
|
||||||
unicode-width.workspace = true
|
|
||||||
unicode-segmentation.workspace = true
|
|
||||||
unicode-linebreak.workspace = true
|
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
thing-testkit = { path = "../thing-testkit" }
|
|
||||||
|
|
@ -1,172 +0,0 @@
|
||||||
//! Format: total and locale-free. Each function takes the value the site read and returns the
|
|
||||||
//! text, or the reason the value does not fit (a detail that never carries the value).
|
|
||||||
|
|
||||||
use thing_contract::{AffixFormat, NumberFormat, is_timestamp_text};
|
|
||||||
|
|
||||||
/// Fixed-point text of `n` at `format.precision`, scaled by 100 for a percent, with the percent
|
|
||||||
/// sign and the unit. Non-finite numbers print as NaN, inf, -inf; negative zero prints as zero.
|
|
||||||
pub fn number(n: f64, format: &NumberFormat) -> String {
|
|
||||||
let scaled = if format.percent { n * 100.0 } else { n };
|
|
||||||
let mut text = if scaled.is_nan() {
|
|
||||||
"NaN".to_string()
|
|
||||||
} else if scaled.is_infinite() {
|
|
||||||
if scaled > 0.0 { "inf" } else { "-inf" }.to_string()
|
|
||||||
} else {
|
|
||||||
format!("{scaled:.*}", format.precision.get() as usize)
|
|
||||||
};
|
|
||||||
if text.starts_with('-') && text[1..].bytes().all(|byte| byte == b'0' || byte == b'.') {
|
|
||||||
text.remove(0);
|
|
||||||
}
|
|
||||||
if format.percent {
|
|
||||||
text.push('%');
|
|
||||||
}
|
|
||||||
if let Some(unit) = &format.unit {
|
|
||||||
text.push(' ');
|
|
||||||
text.push_str(unit);
|
|
||||||
}
|
|
||||||
text
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Seconds rounded half away from zero, printed by the largest unit present with the later
|
|
||||||
/// units at two digits: `5s`, `1m 05s`, `1h 00m 05s`, `1d 01h 00m 00s`, a leading `-` when negative.
|
|
||||||
pub fn duration(seconds: f64) -> Result<String, &'static str> {
|
|
||||||
if !seconds.is_finite() {
|
|
||||||
return Err("a duration is not finite");
|
|
||||||
}
|
|
||||||
let total = seconds.round() as i128;
|
|
||||||
let t = total.unsigned_abs();
|
|
||||||
let (days, hours, minutes, secs) = (t / 86_400, t % 86_400 / 3_600, t % 3_600 / 60, t % 60);
|
|
||||||
let body = if days > 0 {
|
|
||||||
format!("{days}d {hours:02}h {minutes:02}m {secs:02}s")
|
|
||||||
} else if hours > 0 {
|
|
||||||
format!("{hours}h {minutes:02}m {secs:02}s")
|
|
||||||
} else if minutes > 0 {
|
|
||||||
format!("{minutes}m {secs:02}s")
|
|
||||||
} else {
|
|
||||||
format!("{secs}s")
|
|
||||||
};
|
|
||||||
Ok(if total < 0 { format!("-{body}") } else { body })
|
|
||||||
}
|
|
||||||
|
|
||||||
const FIRST_SECOND: i128 = -62_135_596_800; // 0001-01-01T00:00:00Z
|
|
||||||
const LAST_SECOND: i128 = 253_402_300_799; // 9999-12-31T23:59:59Z
|
|
||||||
|
|
||||||
/// Unix seconds, floored, as `YYYY-MM-DDTHH:MM:SSZ` in UTC, years 0001 to 9999.
|
|
||||||
pub fn timestamp(seconds: f64) -> Result<String, &'static str> {
|
|
||||||
if !seconds.is_finite() {
|
|
||||||
return Err("a timestamp is not finite");
|
|
||||||
}
|
|
||||||
let floored = seconds.floor() as i128;
|
|
||||||
if !(FIRST_SECOND..=LAST_SECOND).contains(&floored) {
|
|
||||||
return Err("a timestamp is outside years 0001 to 9999");
|
|
||||||
}
|
|
||||||
let (days, rest) = (floored.div_euclid(86_400), floored.rem_euclid(86_400));
|
|
||||||
let (year, month, day) = civil(days as i64);
|
|
||||||
Ok(format!("{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z", rest / 3_600, rest % 3_600 / 60, rest % 60))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Days since 1970-01-01 as a proleptic Gregorian date.
|
|
||||||
fn civil(days: i64) -> (i64, i64, i64) {
|
|
||||||
let z = days + 719_468;
|
|
||||||
let era = z.div_euclid(146_097);
|
|
||||||
let day_of_era = z.rem_euclid(146_097);
|
|
||||||
let year_of_era = (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
|
|
||||||
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
|
|
||||||
let month_index = (5 * day_of_year + 2) / 153;
|
|
||||||
let day = day_of_year - (153 * month_index + 2) / 5 + 1;
|
|
||||||
let month = if month_index < 10 { month_index + 3 } else { month_index - 9 };
|
|
||||||
(year_of_era + era * 400 + i64::from(month <= 2), month, day)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Text that is already a `stored_at` stamp, as written.
|
|
||||||
pub fn stamp(text: &str) -> Result<String, &'static str> {
|
|
||||||
if is_timestamp_text(text) { Ok(text.to_string()) } else { Err("the text is not a timestamp") }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn affix(text: &str, format: &AffixFormat) -> String {
|
|
||||||
format!("{}{text}{}", format.prefix, format.suffix)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use thing_contract::Count;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn fmt(precision: i32, percent: bool, unit: Option<&str>) -> NumberFormat {
|
|
||||||
NumberFormat { precision: Count::new(precision).unwrap(), percent, unit: unit.map(Into::into) }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn number_table() {
|
|
||||||
let table = [
|
|
||||||
(0.42, fmt(1, true, None), "42.0%"),
|
|
||||||
(3.14159, fmt(2, false, None), "3.14"),
|
|
||||||
(2.5, fmt(0, false, None), "2"),
|
|
||||||
(1234.5, fmt(1, false, Some("MB")), "1234.5 MB"),
|
|
||||||
(0.5, fmt(0, true, Some("of cap")), "50% of cap"),
|
|
||||||
(-0.0, fmt(1, false, None), "0.0"),
|
|
||||||
(-0.04, fmt(1, false, None), "0.0"),
|
|
||||||
(-1.25, fmt(1, false, None), "-1.2"),
|
|
||||||
(f64::NAN, fmt(2, true, None), "NaN%"),
|
|
||||||
(f64::INFINITY, fmt(2, false, Some("x")), "inf x"),
|
|
||||||
(f64::NEG_INFINITY, fmt(0, false, None), "-inf"),
|
|
||||||
];
|
|
||||||
for (n, format, expected) in table {
|
|
||||||
assert_eq!(number(n, &format), expected, "{n} {format:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn duration_table() {
|
|
||||||
let table = [
|
|
||||||
(0.0, "0s"),
|
|
||||||
(5.0, "5s"),
|
|
||||||
(59.4, "59s"),
|
|
||||||
(59.5, "1m 00s"),
|
|
||||||
(65.0, "1m 05s"),
|
|
||||||
(3605.0, "1h 00m 05s"),
|
|
||||||
(90_000.0, "1d 01h 00m 00s"),
|
|
||||||
(-65.0, "-1m 05s"),
|
|
||||||
(-0.4, "0s"),
|
|
||||||
(-0.5, "-1s"),
|
|
||||||
];
|
|
||||||
for (seconds, expected) in table {
|
|
||||||
assert_eq!(duration(seconds).unwrap(), expected, "{seconds}");
|
|
||||||
}
|
|
||||||
assert!(duration(f64::NAN).is_err() && duration(f64::INFINITY).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn timestamp_table() {
|
|
||||||
let table = [
|
|
||||||
(0.0, "1970-01-01T00:00:00Z"),
|
|
||||||
(0.9, "1970-01-01T00:00:00Z"),
|
|
||||||
(-0.1, "1969-12-31T23:59:59Z"),
|
|
||||||
(951_782_400.0, "2000-02-29T00:00:00Z"),
|
|
||||||
(1_767_225_600.0, "2026-01-01T00:00:00Z"),
|
|
||||||
(-62_135_596_800.0, "0001-01-01T00:00:00Z"),
|
|
||||||
(253_402_300_799.0, "9999-12-31T23:59:59Z"),
|
|
||||||
];
|
|
||||||
for (seconds, expected) in table {
|
|
||||||
assert_eq!(timestamp(seconds).unwrap(), expected, "{seconds}");
|
|
||||||
}
|
|
||||||
assert!(timestamp(253_402_300_800.0).is_err());
|
|
||||||
assert!(timestamp(-62_135_596_801.0).is_err());
|
|
||||||
assert!(timestamp(f64::NAN).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn stamp_text_is_printed_as_written() {
|
|
||||||
assert_eq!(stamp("2026-01-01T00:00:00Z").unwrap(), "2026-01-01T00:00:00Z");
|
|
||||||
assert_eq!(stamp("2026-01-01T02:00:00.5+02:00").unwrap(), "2026-01-01T02:00:00.5+02:00");
|
|
||||||
assert!(stamp("yesterday").is_err());
|
|
||||||
assert!(stamp("2026-01-01 00:00:00Z").is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn affix_wraps_text() {
|
|
||||||
let format = AffixFormat { prefix: "[".into(), suffix: "]".into() };
|
|
||||||
assert_eq!(affix("ok", &format), "[ok]");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,368 +0,0 @@
|
||||||
//! Bind: a `ResolvedTree` and provider state become a `BoundTree`, the value of every source
|
|
||||||
//! site of every node, the instances of every Repeat and the typed faults between. The Binder is
|
|
||||||
//! handed trees and the changes the frame owner drained; it never drains, never decodes and keeps
|
|
||||||
//! no state value beside the port: a changed address is read again. The state interests it holds
|
|
||||||
//! are exactly the ones the bound trees read, held through the shared `Ledger`.
|
|
||||||
//!
|
|
||||||
//! A bound tree is a side table over the resolved document, not a second node tree.
|
|
||||||
|
|
||||||
mod format;
|
|
||||||
mod repeat;
|
|
||||||
mod scope;
|
|
||||||
mod walk;
|
|
||||||
|
|
||||||
pub use scope::Located;
|
|
||||||
|
|
||||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
|
||||||
|
|
||||||
use thing_contract::{AssetEntry, NodeId, SelectOption};
|
|
||||||
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
use crate::port::{Address, Change, Interest, Ledger, StatePort};
|
|
||||||
use crate::resolve::{Limits, ResolvedTree};
|
|
||||||
use walk::{Unit, Walker};
|
|
||||||
|
|
||||||
/// Every source site a node can carry. Closed.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
|
||||||
pub enum Field {
|
|
||||||
Visible,
|
|
||||||
A11yLabel,
|
|
||||||
Content,
|
|
||||||
Alt,
|
|
||||||
Enabled,
|
|
||||||
Checked,
|
|
||||||
Value,
|
|
||||||
Placeholder,
|
|
||||||
Initial,
|
|
||||||
Selected,
|
|
||||||
Options,
|
|
||||||
Series,
|
|
||||||
Asset,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Field {
|
|
||||||
pub fn name(self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
Field::Visible => "visible",
|
|
||||||
Field::A11yLabel => "a11y_label",
|
|
||||||
Field::Content => "content",
|
|
||||||
Field::Alt => "alt",
|
|
||||||
Field::Enabled => "enabled",
|
|
||||||
Field::Checked => "checked",
|
|
||||||
Field::Value => "value",
|
|
||||||
Field::Placeholder => "placeholder",
|
|
||||||
Field::Initial => "initial",
|
|
||||||
Field::Selected => "selected",
|
|
||||||
Field::Options => "options",
|
|
||||||
Field::Series => "series",
|
|
||||||
Field::Asset => "asset",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Why a site or a Repeat has no value. `detail` names the fault and never carries a state value.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub struct BindError {
|
|
||||||
pub code: Code,
|
|
||||||
pub detail: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What one site shows. A value is never coerced into another site type.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub enum Bound {
|
|
||||||
Text(String),
|
|
||||||
Number(f64),
|
|
||||||
Bool(bool),
|
|
||||||
Series(Vec<f64>),
|
|
||||||
Options(Vec<SelectOption>),
|
|
||||||
/// The catalog entry an Image names.
|
|
||||||
Asset(AssetEntry),
|
|
||||||
/// The record or the member is not there (or is nil).
|
|
||||||
Absent,
|
|
||||||
Error(BindError),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One instance of a Repeat's template: its key, and the template with derived ids, whose sites
|
|
||||||
/// are in the same table. A refused item's key is `!` and its record key.
|
|
||||||
///
|
|
||||||
/// The one id scheme is `scope_prefix`: an id inside an instance is its prefix followed by the
|
|
||||||
/// template's id, so a node in nested instances is the inner prefix, then the outer, then its declared id.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct Instance {
|
|
||||||
pub key: String,
|
|
||||||
/// What `Instance::scope_prefix` derived for this instance: each of the template's ids is this followed by the template id.
|
|
||||||
pub prefix: String,
|
|
||||||
pub root: thing_contract::Node,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The values of one resolved document.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct BoundTree {
|
|
||||||
tree: ResolvedTree,
|
|
||||||
values: HashMap<(NodeId, Field), Bound>,
|
|
||||||
instances: HashMap<NodeId, Vec<Instance>>,
|
|
||||||
repeat_errors: HashMap<NodeId, BindError>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl BoundTree {
|
|
||||||
pub fn resolved(&self) -> &ResolvedTree {
|
|
||||||
&self.tree
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn value(&self, node: &NodeId, field: Field) -> Option<&Bound> {
|
|
||||||
self.values.get(&(node.clone(), field))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The instances of a Repeat, in collection order; none when the Repeat is in error.
|
|
||||||
pub fn instances(&self, repeat: &NodeId) -> &[Instance] {
|
|
||||||
self.instances.get(repeat).map_or(&[], Vec::as_slice)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Why a Repeat has no instances, when it is in error.
|
|
||||||
pub fn repeat_error(&self, repeat: &NodeId) -> Option<&BindError> {
|
|
||||||
self.repeat_errors.get(repeat)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every bound site, instances' included, sorted by node id and field.
|
|
||||||
pub fn sites(&self) -> Vec<(&NodeId, Field, &Bound)> {
|
|
||||||
let mut sites: Vec<_> = self.values.iter().map(|((node, field), bound)| (node, *field, bound)).collect();
|
|
||||||
sites.sort_by(|a, b| (a.0.as_str(), a.1).cmp(&(b.0.as_str(), b.1)));
|
|
||||||
sites
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What one bind or apply changed: per surface key, the node ids whose value changed (appeared,
|
|
||||||
/// vanished or differed) or whose Repeat instance set changed; and the diagnostics of sites that
|
|
||||||
/// entered an error or changed error code.
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq)]
|
|
||||||
pub struct Applied {
|
|
||||||
pub dirty: BTreeMap<String, Vec<NodeId>>,
|
|
||||||
pub diagnostics: Vec<Diagnostic>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What a surface's unit read and owns, so a unit can be replaced alone.
|
|
||||||
struct Owned {
|
|
||||||
values: Vec<(NodeId, Field)>,
|
|
||||||
repeats: Vec<NodeId>,
|
|
||||||
ids: Vec<NodeId>,
|
|
||||||
nodes: usize,
|
|
||||||
interests: HashSet<Interest>,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Surface {
|
|
||||||
key: String,
|
|
||||||
bound: BoundTree,
|
|
||||||
tree_ids: HashSet<NodeId>,
|
|
||||||
parts: HashMap<Unit, Owned>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Binder {
|
|
||||||
limits: Limits,
|
|
||||||
surfaces: HashMap<String, Surface>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn tree_ids(tree: &ResolvedTree) -> HashSet<NodeId> {
|
|
||||||
fn visit(node: &thing_contract::Node, out: &mut HashSet<NodeId>) {
|
|
||||||
crate::resolve::grow(|| {
|
|
||||||
out.extend(walk::common(node).map(|common| common.id.clone()));
|
|
||||||
if let thing_contract::Node::Repeat(repeat) = node {
|
|
||||||
visit(&repeat.template, out);
|
|
||||||
}
|
|
||||||
walk::children(node).iter().for_each(|child| visit(child, out));
|
|
||||||
})
|
|
||||||
}
|
|
||||||
let mut ids = HashSet::new();
|
|
||||||
visit(&tree.document().root, &mut ids);
|
|
||||||
ids
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Surface {
|
|
||||||
fn interests(&self) -> HashSet<Interest> {
|
|
||||||
self.parts.values().flat_map(|owned| owned.interests.iter().cloned()).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Bind the units `only` selects (all when `None`), replace what they owned, and report what
|
|
||||||
/// changed against what they held.
|
|
||||||
fn run(
|
|
||||||
&mut self,
|
|
||||||
limits: &Limits,
|
|
||||||
port: &mut dyn StatePort,
|
|
||||||
ledger: &mut Ledger,
|
|
||||||
only: Option<&HashSet<Unit>>,
|
|
||||||
) -> (Vec<NodeId>, Vec<Diagnostic>) {
|
|
||||||
let before = self.interests();
|
|
||||||
let mut old_values: HashMap<(NodeId, Field), Bound> = HashMap::new();
|
|
||||||
let mut old_keys: HashMap<NodeId, Vec<String>> = HashMap::new();
|
|
||||||
let mut old_errors: HashMap<NodeId, Code> = HashMap::new();
|
|
||||||
let retired: Vec<Unit> = match only {
|
|
||||||
None => self.parts.keys().cloned().collect(),
|
|
||||||
Some(only) => only.iter().filter(|unit| self.parts.contains_key(*unit)).cloned().collect(),
|
|
||||||
};
|
|
||||||
for unit in retired {
|
|
||||||
let Some(owned) = self.parts.remove(&unit) else { continue };
|
|
||||||
for key in owned.values {
|
|
||||||
if let Some(bound) = self.bound.values.remove(&key) {
|
|
||||||
old_values.insert(key, bound);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for repeat in owned.repeats {
|
|
||||||
if let Some(instances) = self.bound.instances.remove(&repeat) {
|
|
||||||
old_keys.insert(repeat.clone(), instances.into_iter().map(|instance| instance.key).collect());
|
|
||||||
}
|
|
||||||
if let Some(error) = self.bound.repeat_errors.remove(&repeat) {
|
|
||||||
old_errors.insert(repeat, error.code);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut taken = self.tree_ids.clone();
|
|
||||||
let mut spent = 0;
|
|
||||||
for owned in self.parts.values() {
|
|
||||||
taken.extend(owned.ids.iter().cloned());
|
|
||||||
spent += owned.nodes;
|
|
||||||
}
|
|
||||||
let provider = self.bound.tree.document().provider_id.clone();
|
|
||||||
let parts = Walker::new(&*port, &provider, limits, taken, limits.max_nodes.saturating_sub(spent), only)
|
|
||||||
.run(&self.bound.tree.document().root);
|
|
||||||
|
|
||||||
let mut diagnostics = Vec::new();
|
|
||||||
let mut dirty: Vec<NodeId> = Vec::new();
|
|
||||||
let mut note = |node: &NodeId, code: Code, detail: &str, was: Option<Code>| {
|
|
||||||
if was != Some(code) {
|
|
||||||
diagnostics.push(Diagnostic { code, surface: self.key.clone(), node: Some(node.clone()), detail: detail.to_string() });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
for (unit, part) in parts {
|
|
||||||
let mut owned = Owned {
|
|
||||||
values: Vec::new(),
|
|
||||||
repeats: Vec::new(),
|
|
||||||
ids: part.ids,
|
|
||||||
nodes: part.nodes,
|
|
||||||
interests: part.interests,
|
|
||||||
};
|
|
||||||
for (key, bound) in part.values {
|
|
||||||
let old = old_values.remove(&key);
|
|
||||||
if old.as_ref() != Some(&bound) {
|
|
||||||
dirty.push(key.0.clone());
|
|
||||||
}
|
|
||||||
if let Bound::Error(error) = &bound {
|
|
||||||
note(&key.0, error.code, &error.detail, match &old {
|
|
||||||
Some(Bound::Error(was)) => Some(was.code),
|
|
||||||
_ => None,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
owned.values.push(key.clone());
|
|
||||||
self.bound.values.insert(key, bound);
|
|
||||||
}
|
|
||||||
for (repeat, error) in part.errors {
|
|
||||||
note(&repeat, error.code, &error.detail, old_errors.get(&repeat).copied());
|
|
||||||
self.bound.repeat_errors.insert(repeat, error);
|
|
||||||
}
|
|
||||||
for (repeat, instances) in part.instances {
|
|
||||||
let keys: Vec<String> = instances.iter().map(|instance| instance.key.clone()).collect();
|
|
||||||
if old_keys.remove(&repeat).as_ref() != Some(&keys) {
|
|
||||||
dirty.push(repeat.clone());
|
|
||||||
}
|
|
||||||
owned.repeats.push(repeat.clone());
|
|
||||||
self.bound.instances.insert(repeat, instances);
|
|
||||||
}
|
|
||||||
self.parts.insert(unit, owned);
|
|
||||||
}
|
|
||||||
// What the retired units held and the new ones no longer do has vanished.
|
|
||||||
dirty.extend(old_values.into_keys().map(|(node, _)| node));
|
|
||||||
dirty.extend(old_keys.into_keys());
|
|
||||||
|
|
||||||
ledger.diff(port, &before, &self.interests());
|
|
||||||
let mut seen = HashSet::new();
|
|
||||||
dirty.retain(|node| seen.insert(node.clone()));
|
|
||||||
dirty.sort_by(|a, b| a.as_str().cmp(b.as_str()));
|
|
||||||
(dirty, diagnostics)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn matching(&self, address: &Address) -> HashSet<Unit> {
|
|
||||||
self.parts
|
|
||||||
.iter()
|
|
||||||
.filter(|(_, owned)| owned.interests.iter().any(|interest| interest.matches(address)))
|
|
||||||
.map(|(unit, _)| unit.clone())
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Binder {
|
|
||||||
pub fn new(limits: Limits) -> Self {
|
|
||||||
Self { limits, surfaces: HashMap::new() }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Bind a resolved tree. A tree for a surface already held replaces its tree: the walk, the
|
|
||||||
/// diff against what was bound and the interest diff are the same as an apply's.
|
|
||||||
pub fn bind(&mut self, tree: ResolvedTree, port: &mut dyn StatePort, ledger: &mut Ledger) -> Applied {
|
|
||||||
let key = tree.document().record_key();
|
|
||||||
let ids = tree_ids(&tree);
|
|
||||||
let surface = self.surfaces.entry(key.clone()).or_insert_with(|| Surface {
|
|
||||||
key: key.clone(),
|
|
||||||
bound: BoundTree {
|
|
||||||
tree: tree.clone(),
|
|
||||||
values: HashMap::new(),
|
|
||||||
instances: HashMap::new(),
|
|
||||||
repeat_errors: HashMap::new(),
|
|
||||||
},
|
|
||||||
tree_ids: HashSet::new(),
|
|
||||||
parts: HashMap::new(),
|
|
||||||
});
|
|
||||||
surface.bound.tree = tree;
|
|
||||||
surface.tree_ids = ids;
|
|
||||||
let (dirty, diagnostics) = surface.run(&self.limits, port, ledger, None);
|
|
||||||
Applied { dirty: BTreeMap::from([(key, dirty)]).into_iter().filter(|(_, ids)| !ids.is_empty()).collect(), diagnostics }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One drained change: nothing is read unless a held interest matches its address; then each
|
|
||||||
/// unit that read it is bound again from the port.
|
|
||||||
pub fn apply(&mut self, change: &Change, port: &mut dyn StatePort, ledger: &mut Ledger) -> Applied {
|
|
||||||
let address = match change {
|
|
||||||
Change::Upsert(entry) => &entry.address,
|
|
||||||
Change::Delete(address) => address,
|
|
||||||
Change::Refused(refusal) => &refusal.address,
|
|
||||||
};
|
|
||||||
let mut applied = Applied::default();
|
|
||||||
let mut keys: Vec<String> = self.surfaces.keys().cloned().collect();
|
|
||||||
keys.sort();
|
|
||||||
for key in keys {
|
|
||||||
let surface = self.surfaces.get_mut(&key).expect("key listed");
|
|
||||||
let units = surface.matching(address);
|
|
||||||
if units.is_empty() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let (dirty, diagnostics) = surface.run(&self.limits, port, ledger, Some(&units));
|
|
||||||
if !dirty.is_empty() {
|
|
||||||
applied.dirty.insert(key, dirty);
|
|
||||||
}
|
|
||||||
applied.diagnostics.extend(diagnostics);
|
|
||||||
}
|
|
||||||
applied
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Drop a surface: its interests are released.
|
|
||||||
pub fn forget(&mut self, surface: &str, port: &mut dyn StatePort, ledger: &mut Ledger) {
|
|
||||||
if let Some(surface) = self.surfaces.remove(surface) {
|
|
||||||
ledger.diff(port, &surface.interests(), &HashSet::new());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn tree(&self, surface: &str) -> Option<&BoundTree> {
|
|
||||||
self.surfaces.get(surface).map(|surface| &surface.bound)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Instance {
|
|
||||||
/// The prefix of every id of the instance of `repeat` (a laid id) whose key is `key`:
|
|
||||||
/// `<repeat>#<key byte length>:<key>/`; an item the port refused has no key to read, so its
|
|
||||||
/// identity is its record key in the distinct form `<repeat>!<length>:<record key>/`. Resolve's
|
|
||||||
/// instance ids and command captures both derive scope here, so there is one scheme.
|
|
||||||
pub fn scope_prefix(repeat: &str, key: &str, refused: bool) -> String {
|
|
||||||
if refused {
|
|
||||||
format!("{repeat}!{}:{key}/", key.len())
|
|
||||||
} else {
|
|
||||||
format!("{repeat}#{}:{key}/", key.len())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,200 +0,0 @@
|
||||||
//! Repeat: a collection's items become instances of the template, keyed so identity follows the
|
|
||||||
//! item. An instance's ids derive from (repeat id, key, template id) by one scheme:
|
|
||||||
//! `<repeat>#<key byte length>:<key>/<template id>`; an item the port refused has no key to read,
|
|
||||||
//! so its identity is its record key in the distinct form `<repeat>!<length>:<record key>/<template id>`.
|
|
||||||
//! A Repeat that cannot be instantiated is an error of that Repeat alone.
|
|
||||||
|
|
||||||
use std::collections::HashSet;
|
|
||||||
|
|
||||||
use thing_contract::*;
|
|
||||||
|
|
||||||
use super::walk::{Item, Walker, children, common, fault, walk};
|
|
||||||
use super::{BindError, Instance};
|
|
||||||
use crate::diagnostic::Code;
|
|
||||||
use crate::port::{Lookup, Prefix, Record, StateValue};
|
|
||||||
use crate::resolve::grow;
|
|
||||||
|
|
||||||
/// One item of a collection. `record_key` is set for an item that is a record of its own.
|
|
||||||
pub(super) struct Entry {
|
|
||||||
pub record_key: Option<String>,
|
|
||||||
pub item: Item,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The key of an item: Text as it is, an Int in decimal.
|
|
||||||
fn key_of(value: &StateValue, path: &MemberPath) -> Result<String, BindError> {
|
|
||||||
match walk(value, path)? {
|
|
||||||
Some(StateValue::Text(text)) => Ok(text.clone()),
|
|
||||||
Some(StateValue::Int(n)) => Ok(n.to_string()),
|
|
||||||
Some(_) => Err(fault(Code::BindTypeMismatch, "an item key is not Text or Int")),
|
|
||||||
None => Err(fault(Code::BindTypeMismatch, "an item key is nil")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn collect_ids(node: &Node, out: &mut Vec<NodeId>) {
|
|
||||||
grow(|| {
|
|
||||||
out.extend(common(node).map(|common| common.id.clone()));
|
|
||||||
if let Node::Repeat(repeat) = node {
|
|
||||||
collect_ids(&repeat.template, out);
|
|
||||||
}
|
|
||||||
children(node).iter().for_each(|child| collect_ids(child, out));
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Give every id of the template, and every anchor that names one of them, the instance prefix.
|
|
||||||
fn rewrite(node: &mut Node, prefix: &str, inside: &HashSet<NodeId>) {
|
|
||||||
grow(|| {
|
|
||||||
let derive = |id: &mut NodeId| *id = NodeId::new(format!("{prefix}{}", id.as_str()));
|
|
||||||
match node {
|
|
||||||
Node::Box(n) => {
|
|
||||||
derive(&mut n.common.id);
|
|
||||||
n.children.iter_mut().for_each(|child| rewrite(child, prefix, inside));
|
|
||||||
}
|
|
||||||
Node::Button(n) => {
|
|
||||||
derive(&mut n.common.id);
|
|
||||||
n.content.iter_mut().for_each(|child| rewrite(child, prefix, inside));
|
|
||||||
}
|
|
||||||
Node::Overlay(n) => {
|
|
||||||
derive(&mut n.common.id);
|
|
||||||
if let Anchor::Node(anchor) = &mut n.anchor {
|
|
||||||
if inside.contains(&anchor.node) {
|
|
||||||
derive(&mut anchor.node);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
n.children.iter_mut().for_each(|child| rewrite(child, prefix, inside));
|
|
||||||
}
|
|
||||||
Node::Repeat(n) => {
|
|
||||||
derive(&mut n.common.id);
|
|
||||||
rewrite(&mut n.template, prefix, inside);
|
|
||||||
}
|
|
||||||
Node::Text(n) => derive(&mut n.common.id),
|
|
||||||
Node::Image(n) => derive(&mut n.common.id),
|
|
||||||
Node::Toggle(n) => derive(&mut n.common.id),
|
|
||||||
Node::Slider(n) => derive(&mut n.common.id),
|
|
||||||
Node::TextInput(n) => derive(&mut n.common.id),
|
|
||||||
Node::Select(n) => derive(&mut n.common.id),
|
|
||||||
Node::Plot(n) => derive(&mut n.common.id),
|
|
||||||
Node::Embed(n) => derive(&mut n.common.id),
|
|
||||||
Node::Use(n) => derive(&mut n.common.id),
|
|
||||||
Node::Slot(_) => {}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Walker<'_> {
|
|
||||||
/// The items of a collection, each a value or the fault that stands for it. Records read the
|
|
||||||
/// prefix, a Member reads the list of its holder; both leave their interest.
|
|
||||||
pub(super) fn collection(&mut self, source: &CollectionSource, item: Option<&Item>) -> Result<Vec<Entry>, BindError> {
|
|
||||||
match source {
|
|
||||||
CollectionSource::Records(records) => {
|
|
||||||
let provider = records.provider.clone().unwrap_or_else(|| self.provider.clone());
|
|
||||||
let prefix = Prefix { provider, schema: records.schema.clone(), key_prefix: records.key_prefix.clone() };
|
|
||||||
self.part.interests.insert(crate::port::Interest::Prefix(prefix.clone()));
|
|
||||||
Ok(self
|
|
||||||
.port
|
|
||||||
.list(&prefix)
|
|
||||||
.into_iter()
|
|
||||||
.filter_map(|lookup| match lookup {
|
|
||||||
Lookup::Present(entry) => {
|
|
||||||
let record_key = Some(entry.address.key.as_str().to_string());
|
|
||||||
Some(match entry.record {
|
|
||||||
Record::State { schema, value } if schema == records.schema => {
|
|
||||||
Entry { record_key, item: Item::Value(value) }
|
|
||||||
}
|
|
||||||
_ => Entry {
|
|
||||||
record_key,
|
|
||||||
item: Item::Fault(fault(
|
|
||||||
Code::BindSchemaMismatch,
|
|
||||||
format!("the record is not held under {}", records.schema.as_str()),
|
|
||||||
)),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
Lookup::Refused(refusal) => Some(Entry {
|
|
||||||
record_key: Some(refusal.address.key.as_str().to_string()),
|
|
||||||
item: Item::Fault(fault(Code::DecodeRefused, refusal.detail)),
|
|
||||||
}),
|
|
||||||
Lookup::Absent => None,
|
|
||||||
})
|
|
||||||
.collect())
|
|
||||||
}
|
|
||||||
CollectionSource::Member(bind) => self.with_source(&bind.source, item, |held| match held? {
|
|
||||||
None => Ok(Vec::new()),
|
|
||||||
Some(holder) => match walk(holder, &bind.member)? {
|
|
||||||
None => Ok(Vec::new()),
|
|
||||||
Some(StateValue::List(items)) => Ok(items
|
|
||||||
.iter()
|
|
||||||
.map(|value| Entry { record_key: None, item: Item::Value(value.clone()) })
|
|
||||||
.collect()),
|
|
||||||
Some(_) => Err(fault(Code::BindTypeMismatch, "a collection member is not a list")),
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
CollectionSource::Param(_) => {
|
|
||||||
Err(fault(Code::BindTypeMismatch, "a parameter that resolve left in the tree"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Bind the instances of one Repeat, whole or not at all.
|
|
||||||
pub(super) fn repeat(&mut self, repeat: &RepeatNode, outer: Option<&Item>) {
|
|
||||||
let id = repeat.common.id.clone();
|
|
||||||
match self.instances(repeat, outer) {
|
|
||||||
Ok(instances) => self.part.instances.push((id, instances)),
|
|
||||||
Err(error) => {
|
|
||||||
self.part.errors.push((id.clone(), error));
|
|
||||||
self.part.instances.push((id, Vec::new()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn instances(&mut self, repeat: &RepeatNode, outer: Option<&Item>) -> Result<Vec<Instance>, BindError> {
|
|
||||||
let entries = self.collection(&repeat.collection, outer)?;
|
|
||||||
let id = repeat.common.id.as_str();
|
|
||||||
let mut template_ids = Vec::new();
|
|
||||||
collect_ids(&repeat.template, &mut template_ids);
|
|
||||||
let inside: HashSet<NodeId> = template_ids.into_iter().collect();
|
|
||||||
|
|
||||||
let mut keys = HashSet::new();
|
|
||||||
let mut built: Vec<(Instance, Item)> = Vec::with_capacity(entries.len());
|
|
||||||
for entry in entries {
|
|
||||||
let (key, prefix) = match &entry.item {
|
|
||||||
Item::Fault(_) => {
|
|
||||||
let record = entry.record_key.clone().unwrap_or_default();
|
|
||||||
let prefix = Instance::scope_prefix(id, &record, true);
|
|
||||||
(format!("!{record}"), prefix)
|
|
||||||
}
|
|
||||||
Item::Value(value) => {
|
|
||||||
let key = key_of(value, &repeat.key_member)?;
|
|
||||||
if !keys.insert(key.clone()) {
|
|
||||||
return Err(fault(Code::RepeatKeyDuplicate, format!("two items of {id} share one key")));
|
|
||||||
}
|
|
||||||
let prefix = Instance::scope_prefix(id, &key, false);
|
|
||||||
(key, prefix)
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let mut root = (*repeat.template).clone();
|
|
||||||
rewrite(&mut root, &prefix, &inside);
|
|
||||||
built.push((Instance { key, prefix, root }, entry.item));
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut ids = Vec::new();
|
|
||||||
for (instance, _) in &built {
|
|
||||||
collect_ids(&instance.root, &mut ids);
|
|
||||||
}
|
|
||||||
if ids.len() > self.budget.min(self.limits.max_nodes) {
|
|
||||||
return Err(fault(Code::ExpansionLimit, format!("the instances of {id} are past the node limit")));
|
|
||||||
}
|
|
||||||
let mut local = HashSet::new();
|
|
||||||
if ids.iter().any(|derived| self.taken.contains(derived) || !local.insert(derived)) {
|
|
||||||
return Err(fault(Code::DuplicateNodeId, format!("an instance id of {id} is already an id of the tree")));
|
|
||||||
}
|
|
||||||
|
|
||||||
self.budget -= ids.len();
|
|
||||||
self.part.nodes += ids.len();
|
|
||||||
self.taken.extend(ids.iter().cloned());
|
|
||||||
self.part.ids.extend(ids);
|
|
||||||
for (instance, item) in &built {
|
|
||||||
self.instance(&instance.root, item);
|
|
||||||
}
|
|
||||||
Ok(built.into_iter().map(|(instance, _)| instance).collect())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,111 +0,0 @@
|
||||||
//! Where a node sits in a bound tree: the one id -> node index, and the Repeat instances that
|
|
||||||
//! enclose a node, which commands read to name a row and to find the inputs beside a button.
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
use thing_contract::{Node, NodeId};
|
|
||||||
|
|
||||||
use super::walk::{children, common};
|
|
||||||
use super::BoundTree;
|
|
||||||
use crate::resolve::grow;
|
|
||||||
|
|
||||||
/// A node and the Repeat instances around it, read off the tree.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct Located<'a> {
|
|
||||||
pub node: &'a Node,
|
|
||||||
/// The id the author declared: the laid id with its instance prefixes removed.
|
|
||||||
pub declared: NodeId,
|
|
||||||
/// The prefix of each enclosing instance, innermost first. An id declared at the top of the
|
|
||||||
/// document, reached from here, is these joined in order followed by it.
|
|
||||||
pub prefixes: Vec<String>,
|
|
||||||
/// The key of each enclosing instance, outermost first.
|
|
||||||
pub items: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Walk<'a, 'b> {
|
|
||||||
tree: &'a BoundTree,
|
|
||||||
prefixes: Vec<&'a str>,
|
|
||||||
items: Vec<&'a str>,
|
|
||||||
visit: &'b mut dyn FnMut(Located<'a>) -> bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> Walk<'a, '_> {
|
|
||||||
/// Visit the node, then what it holds; stops (`true`) as soon as a visit says so.
|
|
||||||
fn node(&mut self, node: &'a Node) -> bool {
|
|
||||||
grow(|| {
|
|
||||||
let Some(common) = common(node) else { return false };
|
|
||||||
let skip: usize = self.prefixes.iter().map(|prefix| prefix.len()).sum();
|
|
||||||
let declared = NodeId::new(common.id.as_str().get(skip..).unwrap_or(common.id.as_str()));
|
|
||||||
let located = Located {
|
|
||||||
node,
|
|
||||||
declared,
|
|
||||||
prefixes: self.prefixes.iter().rev().map(|prefix| prefix.to_string()).collect(),
|
|
||||||
items: self.items.iter().map(|item| item.to_string()).collect(),
|
|
||||||
};
|
|
||||||
if (self.visit)(located) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if let Node::Repeat(repeat) = node {
|
|
||||||
for instance in self.tree.instances(&repeat.common.id) {
|
|
||||||
self.prefixes.push(&instance.prefix);
|
|
||||||
self.items.push(&instance.key);
|
|
||||||
let stop = self.node(&instance.root);
|
|
||||||
self.prefixes.pop();
|
|
||||||
self.items.pop();
|
|
||||||
if stop {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
children(node).iter().any(|child| self.node(child))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl BoundTree {
|
|
||||||
/// Every node of the document by laid id, Repeat instances included (ids are unique after
|
|
||||||
/// resolve). The one index render, hit-test and commands share.
|
|
||||||
pub fn index(&self) -> HashMap<&NodeId, &Node> {
|
|
||||||
let mut found = HashMap::new();
|
|
||||||
self.walk(&mut |located| {
|
|
||||||
if let Some(common) = common(located.node) {
|
|
||||||
found.insert(&common.id, located.node);
|
|
||||||
}
|
|
||||||
false
|
|
||||||
});
|
|
||||||
found
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The node with laid id `id`, and where it sits.
|
|
||||||
pub fn locate(&self, id: &NodeId) -> Option<Located<'_>> {
|
|
||||||
let mut found = None;
|
|
||||||
self.walk(&mut |located| {
|
|
||||||
let hit = common(located.node).is_some_and(|common| &common.id == id);
|
|
||||||
if hit {
|
|
||||||
found = Some(located);
|
|
||||||
}
|
|
||||||
hit
|
|
||||||
});
|
|
||||||
found
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The first node declared as `declared` inside the instances keyed `items` (outermost first).
|
|
||||||
pub fn locate_source(&self, declared: &NodeId, items: &[String]) -> Option<Located<'_>> {
|
|
||||||
let mut found = None;
|
|
||||||
self.walk(&mut |located| {
|
|
||||||
let hit = &located.declared == declared && located.items == items;
|
|
||||||
if hit {
|
|
||||||
found = Some(located);
|
|
||||||
}
|
|
||||||
hit
|
|
||||||
});
|
|
||||||
found
|
|
||||||
}
|
|
||||||
|
|
||||||
fn walk<'a>(&'a self, visit: &mut dyn FnMut(Located<'a>) -> bool) {
|
|
||||||
let mut walk = Walk { tree: self, prefixes: Vec::new(), items: Vec::new(), visit };
|
|
||||||
walk.node(&self.resolved().document().root);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
@ -1,402 +0,0 @@
|
||||||
//! The walk: every source site of a node, read from the state port, a member path and a terminal
|
|
||||||
//! type. Nothing here keeps a value: the port is the truth.
|
|
||||||
|
|
||||||
use std::collections::HashSet;
|
|
||||||
|
|
||||||
use thing_contract::*;
|
|
||||||
|
|
||||||
use super::format;
|
|
||||||
use super::{BindError, Bound, Field, Instance};
|
|
||||||
use crate::diagnostic::Code;
|
|
||||||
use crate::port::{Address, Entry, Interest, Lookup, Record, StatePort, StateValue};
|
|
||||||
use crate::resolve::{Limits, grow};
|
|
||||||
|
|
||||||
/// What a surface's values are re-evaluated by: one site, or one outermost Repeat (`None`).
|
|
||||||
pub(super) type Unit = (NodeId, Option<Field>);
|
|
||||||
|
|
||||||
/// What one unit bound: its values, its instance lists, its Repeat faults, the ids and node count
|
|
||||||
/// its instances take, and the interests it read.
|
|
||||||
#[derive(Default)]
|
|
||||||
pub(super) struct Part {
|
|
||||||
pub values: Vec<((NodeId, Field), Bound)>,
|
|
||||||
pub instances: Vec<(NodeId, Vec<Instance>)>,
|
|
||||||
pub errors: Vec<(NodeId, BindError)>,
|
|
||||||
pub ids: Vec<NodeId>,
|
|
||||||
pub nodes: usize,
|
|
||||||
pub interests: HashSet<Interest>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The value a Repeat's template reads through `Item`.
|
|
||||||
pub(super) enum Item {
|
|
||||||
Value(StateValue),
|
|
||||||
Fault(BindError),
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn fault(code: Code, detail: impl Into<String>) -> BindError {
|
|
||||||
BindError { code, detail: detail.into() }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub(super) enum Want {
|
|
||||||
Text,
|
|
||||||
Number,
|
|
||||||
Bool,
|
|
||||||
Series,
|
|
||||||
}
|
|
||||||
|
|
||||||
enum Site<'n> {
|
|
||||||
Bool(&'n BoolSource),
|
|
||||||
Text(&'n TextSource),
|
|
||||||
Number(&'n NumberSource),
|
|
||||||
Bind(&'n Bind, Want),
|
|
||||||
Options(&'n OptionList),
|
|
||||||
Asset(&'n ImageNode),
|
|
||||||
}
|
|
||||||
|
|
||||||
fn kind(value: &StateValue) -> &'static str {
|
|
||||||
match value {
|
|
||||||
StateValue::Nil => "nil",
|
|
||||||
StateValue::Bool(_) => "bool",
|
|
||||||
StateValue::Int(_) => "int",
|
|
||||||
StateValue::Float(_) => "float",
|
|
||||||
StateValue::Text(_) => "text",
|
|
||||||
StateValue::Bytes(_) => "bytes",
|
|
||||||
StateValue::List(_) => "list",
|
|
||||||
StateValue::Record(_) => "record",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn number_of(value: &StateValue) -> Option<f64> {
|
|
||||||
match value {
|
|
||||||
StateValue::Int(n) => Some(*n as f64),
|
|
||||||
StateValue::Float(n) => Some(*n),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Walk `path` from `value`. `Ok(None)` is a Nil reached, which is absence.
|
|
||||||
pub(super) fn walk<'v>(mut value: &'v StateValue, path: &MemberPath) -> Result<Option<&'v StateValue>, BindError> {
|
|
||||||
for step in &path.steps {
|
|
||||||
if matches!(value, StateValue::Nil) {
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
value = match (step, value) {
|
|
||||||
(MemberStep::Name(step), StateValue::Record(_)) => value
|
|
||||||
.member(&step.name)
|
|
||||||
.ok_or_else(|| fault(Code::BindMemberMissing, format!("the record has no member {}", step.name)))?,
|
|
||||||
(MemberStep::Index(step), StateValue::List(items)) => items.get(step.index.get() as usize).ok_or_else(|| {
|
|
||||||
fault(Code::BindMemberMissing, format!("the list has no index {}", step.index.get()))
|
|
||||||
})?,
|
|
||||||
(MemberStep::Name(step), other) => {
|
|
||||||
return Err(fault(Code::BindTypeMismatch, format!("member {} asked of a {}", step.name, kind(other))));
|
|
||||||
}
|
|
||||||
(MemberStep::Index(step), other) => {
|
|
||||||
return Err(fault(Code::BindTypeMismatch, format!("index {} asked of a {}", step.index.get(), kind(other))));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
Ok(if matches!(value, StateValue::Nil) { None } else { Some(value) })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A value at the type its site takes. No value is coerced; a Format is the only road from a
|
|
||||||
/// number to text.
|
|
||||||
fn terminal(value: &StateValue, want: Want, format: Option<&Format>) -> Result<Bound, BindError> {
|
|
||||||
let mismatch = |why: &str| Err(fault(Code::BindTypeMismatch, format!("{why}: a {} value", kind(value))));
|
|
||||||
if want != Want::Text && format.is_some() {
|
|
||||||
return mismatch("a Format on a site that is not text");
|
|
||||||
}
|
|
||||||
match want {
|
|
||||||
Want::Number => match number_of(value) {
|
|
||||||
Some(n) => Ok(Bound::Number(n)),
|
|
||||||
None => mismatch("a number site"),
|
|
||||||
},
|
|
||||||
Want::Bool => match value {
|
|
||||||
StateValue::Bool(b) => Ok(Bound::Bool(*b)),
|
|
||||||
_ => mismatch("a bool site"),
|
|
||||||
},
|
|
||||||
Want::Series => match value {
|
|
||||||
StateValue::List(items) => match items.iter().map(number_of).collect::<Option<Vec<f64>>>() {
|
|
||||||
Some(series) => Ok(Bound::Series(series)),
|
|
||||||
None => Err(fault(Code::BindTypeMismatch, "a series holds a member that is not a number")),
|
|
||||||
},
|
|
||||||
_ => mismatch("a series site"),
|
|
||||||
},
|
|
||||||
Want::Text => {
|
|
||||||
let text = match (value, format) {
|
|
||||||
(StateValue::Text(text), None) => Ok(text.clone()),
|
|
||||||
(StateValue::Text(text), Some(Format::Affix(affix))) => Ok(format::affix(text, affix)),
|
|
||||||
(StateValue::Text(text), Some(Format::Timestamp)) => format::stamp(text),
|
|
||||||
(StateValue::Int(_) | StateValue::Float(_), Some(Format::Number(spec))) => {
|
|
||||||
Ok(format::number(number_of(value).unwrap(), spec))
|
|
||||||
}
|
|
||||||
(StateValue::Int(_) | StateValue::Float(_), Some(Format::Duration)) => {
|
|
||||||
format::duration(number_of(value).unwrap())
|
|
||||||
}
|
|
||||||
(StateValue::Int(_) | StateValue::Float(_), Some(Format::Timestamp)) => {
|
|
||||||
format::timestamp(number_of(value).unwrap())
|
|
||||||
}
|
|
||||||
_ => Err("the value does not fit the text site and its Format"),
|
|
||||||
};
|
|
||||||
text.map(Bound::Text).map_err(|why| fault(Code::BindTypeMismatch, format!("{why}: a {} value", kind(value))))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The Text at `path` of an item, for an option's value or label.
|
|
||||||
pub(super) fn item_text(value: &StateValue, path: &MemberPath) -> Result<String, BindError> {
|
|
||||||
match walk(value, path)? {
|
|
||||||
Some(StateValue::Text(text)) => Ok(text.clone()),
|
|
||||||
Some(other) => Err(fault(Code::BindTypeMismatch, format!("an option member is a {}", kind(other)))),
|
|
||||||
None => Err(fault(Code::BindTypeMismatch, "an option member is nil")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The sites of one node, in Field order.
|
|
||||||
fn sites(node: &Node) -> Vec<(Field, Site<'_>)> {
|
|
||||||
let mut found = Vec::new();
|
|
||||||
let Some(common) = common(node) else { return found };
|
|
||||||
found.push((Field::Visible, Site::Bool(&common.visible)));
|
|
||||||
if let Some(label) = &common.a11y_label {
|
|
||||||
found.push((Field::A11yLabel, Site::Text(label)));
|
|
||||||
}
|
|
||||||
match node {
|
|
||||||
Node::Text(n) => found.push((Field::Content, Site::Text(&n.content))),
|
|
||||||
Node::Image(n) => {
|
|
||||||
found.push((Field::Alt, Site::Text(&n.alt)));
|
|
||||||
found.push((Field::Asset, Site::Asset(n)));
|
|
||||||
}
|
|
||||||
Node::Button(n) => found.push((Field::Enabled, Site::Bool(&n.enabled))),
|
|
||||||
Node::Toggle(n) => found.push((Field::Checked, Site::Bool(&n.checked))),
|
|
||||||
Node::Slider(n) => found.push((Field::Value, Site::Number(&n.value))),
|
|
||||||
Node::TextInput(n) => {
|
|
||||||
found.push((Field::Placeholder, Site::Text(&n.placeholder)));
|
|
||||||
found.push((Field::Initial, Site::Text(&n.initial)));
|
|
||||||
}
|
|
||||||
Node::Select(n) => {
|
|
||||||
found.push((Field::Options, Site::Options(&n.options)));
|
|
||||||
found.push((Field::Selected, Site::Bind(&n.value, Want::Text)));
|
|
||||||
}
|
|
||||||
Node::Plot(n) => found.push((Field::Series, Site::Bind(&n.series, Want::Series))),
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
found
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn common(node: &Node) -> Option<&NodeCommon> {
|
|
||||||
Some(match node {
|
|
||||||
Node::Box(n) => &n.common,
|
|
||||||
Node::Text(n) => &n.common,
|
|
||||||
Node::Image(n) => &n.common,
|
|
||||||
Node::Button(n) => &n.common,
|
|
||||||
Node::Toggle(n) => &n.common,
|
|
||||||
Node::Slider(n) => &n.common,
|
|
||||||
Node::TextInput(n) => &n.common,
|
|
||||||
Node::Select(n) => &n.common,
|
|
||||||
Node::Repeat(n) => &n.common,
|
|
||||||
Node::Overlay(n) => &n.common,
|
|
||||||
Node::Plot(n) => &n.common,
|
|
||||||
Node::Embed(n) => &n.common,
|
|
||||||
Node::Use(n) => &n.common,
|
|
||||||
Node::Slot(_) => return None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The children a walk visits: a Repeat's template is instantiated, never visited as itself.
|
|
||||||
pub(super) fn children(node: &Node) -> &[Node] {
|
|
||||||
match node {
|
|
||||||
Node::Box(n) => &n.children,
|
|
||||||
Node::Button(n) => &n.content,
|
|
||||||
Node::Overlay(n) => &n.children,
|
|
||||||
_ => &[],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) struct Walker<'a> {
|
|
||||||
pub(super) port: &'a dyn StatePort,
|
|
||||||
pub(super) provider: &'a ProviderId,
|
|
||||||
pub(super) limits: &'a Limits,
|
|
||||||
/// Every id of the bound tree outside the units being walked, and the ones walked so far.
|
|
||||||
pub(super) taken: HashSet<NodeId>,
|
|
||||||
/// Instance nodes still allowed.
|
|
||||||
pub(super) budget: usize,
|
|
||||||
only: Option<&'a HashSet<Unit>>,
|
|
||||||
pub(super) part: Part,
|
|
||||||
done: Vec<(Unit, Part)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> Walker<'a> {
|
|
||||||
pub(super) fn new(
|
|
||||||
port: &'a dyn StatePort,
|
|
||||||
provider: &'a ProviderId,
|
|
||||||
limits: &'a Limits,
|
|
||||||
taken: HashSet<NodeId>,
|
|
||||||
budget: usize,
|
|
||||||
only: Option<&'a HashSet<Unit>>,
|
|
||||||
) -> Self {
|
|
||||||
Self { port, provider, limits, taken, budget, only, part: Part::default(), done: Vec::new() }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Walk the resolved root, binding every unit `only` selects (all when `None`).
|
|
||||||
pub(super) fn run(mut self, root: &Node) -> Vec<(Unit, Part)> {
|
|
||||||
self.top(root);
|
|
||||||
self.done
|
|
||||||
}
|
|
||||||
|
|
||||||
fn selects(&self, unit: &Unit) -> bool {
|
|
||||||
self.only.is_none_or(|only| only.contains(unit))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn end(&mut self, unit: Unit) {
|
|
||||||
let part = std::mem::take(&mut self.part);
|
|
||||||
self.done.push((unit, part));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn top(&mut self, node: &Node) {
|
|
||||||
grow(|| {
|
|
||||||
let Some(id) = common(node).map(|common| common.id.clone()) else { return };
|
|
||||||
for (field, site) in sites(node) {
|
|
||||||
let unit = (id.clone(), Some(field));
|
|
||||||
if self.selects(&unit) {
|
|
||||||
let value = self.eval(site, None);
|
|
||||||
self.part.values.push(((id.clone(), field), value));
|
|
||||||
self.end(unit);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if let Node::Repeat(repeat) = node {
|
|
||||||
let unit = (id, None);
|
|
||||||
if self.selects(&unit) {
|
|
||||||
self.repeat(repeat, None);
|
|
||||||
self.end(unit);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
children(node).iter().for_each(|child| self.top(child));
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An instance's nodes: every site binds, with `item` as the Item.
|
|
||||||
pub(super) fn instance(&mut self, node: &Node, item: &Item) {
|
|
||||||
grow(|| {
|
|
||||||
let Some(id) = common(node).map(|common| common.id.clone()) else { return };
|
|
||||||
for (field, site) in sites(node) {
|
|
||||||
let value = self.eval(site, Some(item));
|
|
||||||
self.part.values.push(((id.clone(), field), value));
|
|
||||||
}
|
|
||||||
if let Node::Repeat(repeat) = node {
|
|
||||||
self.repeat(repeat, Some(item));
|
|
||||||
} else {
|
|
||||||
children(node).iter().for_each(|child| self.instance(child, item));
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn eval(&mut self, site: Site<'_>, item: Option<&Item>) -> Bound {
|
|
||||||
let unresolved = || Bound::Error(fault(Code::BindTypeMismatch, "a parameter that resolve left in the tree"));
|
|
||||||
match site {
|
|
||||||
Site::Bool(BoolSource::Literal(literal)) => Bound::Bool(literal.value),
|
|
||||||
Site::Bool(BoolSource::Bound(bind)) => self.bind(bind, Want::Bool, item),
|
|
||||||
Site::Text(TextSource::Literal(literal)) => Bound::Text(literal.value.clone()),
|
|
||||||
Site::Text(TextSource::Bound(bind)) => self.bind(bind, Want::Text, item),
|
|
||||||
Site::Number(NumberSource::Literal(literal)) => Bound::Number(literal.value),
|
|
||||||
Site::Number(NumberSource::Bound(bind)) => self.bind(bind, Want::Number, item),
|
|
||||||
Site::Bool(BoolSource::Param(_)) | Site::Text(TextSource::Param(_)) | Site::Number(NumberSource::Param(_)) => {
|
|
||||||
unresolved()
|
|
||||||
}
|
|
||||||
Site::Bind(bind, want) => self.bind(bind, want, item),
|
|
||||||
Site::Options(OptionList::Literal(literal)) => Bound::Options(literal.options.clone()),
|
|
||||||
Site::Options(OptionList::Bound(bound)) => self.options(bound, item),
|
|
||||||
Site::Asset(image) => self.asset(image),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Hand `then` what `source` holds: a fault, absence, or the value. Records the interest a
|
|
||||||
/// Record source reads.
|
|
||||||
pub(super) fn with_source<R>(
|
|
||||||
&mut self,
|
|
||||||
source: &StateSource,
|
|
||||||
item: Option<&Item>,
|
|
||||||
then: impl FnOnce(Result<Option<&StateValue>, BindError>) -> R,
|
|
||||||
) -> R {
|
|
||||||
match source {
|
|
||||||
StateSource::Item => match item {
|
|
||||||
Some(Item::Value(value)) => then(Ok(Some(value))),
|
|
||||||
Some(Item::Fault(error)) => then(Err(error.clone())),
|
|
||||||
None => then(Err(fault(Code::BindTypeMismatch, "an Item source outside a Repeat"))),
|
|
||||||
},
|
|
||||||
StateSource::Record(reference) => {
|
|
||||||
let provider = reference.provider.clone().unwrap_or_else(|| self.provider.clone());
|
|
||||||
let address = Address { provider, schema: reference.schema.clone(), key: reference.key.clone() };
|
|
||||||
self.part.interests.insert(Interest::Record(address.clone()));
|
|
||||||
match self.port.read(&address) {
|
|
||||||
Lookup::Present(Entry { record: Record::State { schema, value }, .. }) if schema == reference.schema => {
|
|
||||||
then(Ok(Some(&value)))
|
|
||||||
}
|
|
||||||
Lookup::Present(_) => then(Err(fault(
|
|
||||||
Code::BindSchemaMismatch,
|
|
||||||
format!("the record is not held under {}", reference.schema.as_str()),
|
|
||||||
))),
|
|
||||||
Lookup::Absent => then(Ok(None)),
|
|
||||||
Lookup::Refused(refusal) => then(Err(fault(Code::DecodeRefused, refusal.detail))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn bind(&mut self, bind: &Bind, want: Want, item: Option<&Item>) -> Bound {
|
|
||||||
self.with_source(&bind.source, item, |held| match held {
|
|
||||||
Err(error) => Bound::Error(error),
|
|
||||||
Ok(None) => Bound::Absent,
|
|
||||||
Ok(Some(value)) => match walk(value, &bind.member) {
|
|
||||||
Err(error) => Bound::Error(error),
|
|
||||||
Ok(None) => Bound::Absent,
|
|
||||||
Ok(Some(value)) => terminal(value, want, bind.format.as_ref()).unwrap_or_else(Bound::Error),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The catalog entry an Image names: the catalog record is one more interest of the Image.
|
|
||||||
fn asset(&mut self, image: &ImageNode) -> Bound {
|
|
||||||
let Ok(catalog) = Segment::new(image.catalog.as_str()) else {
|
|
||||||
return Bound::Error(fault(Code::AssetMissing, "catalog id is not one segment"));
|
|
||||||
};
|
|
||||||
let address = Address {
|
|
||||||
provider: self.provider.clone(),
|
|
||||||
schema: SchemaId::new(AssetCatalog::SCHEMA_NAME),
|
|
||||||
key: RecordKey::new(asset_catalog_key(self.provider, &catalog)),
|
|
||||||
};
|
|
||||||
self.part.interests.insert(Interest::Record(address.clone()));
|
|
||||||
match self.port.read(&address) {
|
|
||||||
Lookup::Present(Entry { record: Record::Catalog(held), .. }) => {
|
|
||||||
match held.assets.into_iter().find(|entry| entry.id == image.asset) {
|
|
||||||
Some(entry) => Bound::Asset(entry),
|
|
||||||
None => Bound::Error(fault(Code::AssetMissing, format!("no asset {} in the catalog", image.asset))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Lookup::Present(_) => Bound::Error(fault(
|
|
||||||
Code::BindSchemaMismatch,
|
|
||||||
format!("the record is not held under {}", AssetCatalog::SCHEMA_NAME),
|
|
||||||
)),
|
|
||||||
Lookup::Absent => Bound::Absent,
|
|
||||||
Lookup::Refused(refusal) => Bound::Error(fault(Code::DecodeRefused, refusal.detail)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn options(&mut self, bound: &BoundOptions, item: Option<&Item>) -> Bound {
|
|
||||||
let entries = match self.collection(&bound.collection, item) {
|
|
||||||
Ok(entries) => entries,
|
|
||||||
Err(error) => return Bound::Error(error),
|
|
||||||
};
|
|
||||||
let mut options = Vec::with_capacity(entries.len());
|
|
||||||
for entry in entries {
|
|
||||||
let value = match entry.item {
|
|
||||||
Item::Value(value) => value,
|
|
||||||
Item::Fault(error) => return Bound::Error(error),
|
|
||||||
};
|
|
||||||
match (item_text(&value, &bound.value_member), item_text(&value, &bound.label_member)) {
|
|
||||||
(Ok(value), Ok(label)) => options.push(SelectOption { value, label }),
|
|
||||||
(Err(error), _) | (_, Err(error)) => return Bound::Error(error),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Bound::Options(options)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,110 +0,0 @@
|
||||||
//! Captures: the values an invocation carries, read at the user's action from the drafts over the
|
|
||||||
//! bound values. An input beside a button in a Repeat row is found by scope: the activating node's
|
|
||||||
//! innermost instance first, then outward, then the declared id itself.
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
use thing_contract::{BoolValue, CapturedInput, ChoiceValue, CommandDecl, InputKind, InputValue, Node, NodeId, NumberValue, TextValue};
|
|
||||||
|
|
||||||
use crate::bind::{Bound, BoundTree, Field};
|
|
||||||
use crate::input::Drafts;
|
|
||||||
|
|
||||||
/// What the captures of one command came to: the values to send, and the drafts they were read from
|
|
||||||
/// (laid id and the value the table held), which a completed result clears if still held.
|
|
||||||
pub(super) struct Captured {
|
|
||||||
pub inputs: Vec<CapturedInput>,
|
|
||||||
pub held: Vec<(NodeId, InputValue)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The laid id of `declared` as seen from a node whose enclosing instance prefixes are `scope`
|
|
||||||
/// (innermost first): the most specific one the tree holds.
|
|
||||||
pub(super) fn laid_id(index: &HashMap<&NodeId, &Node>, scope: &[String], declared: &NodeId) -> Option<NodeId> {
|
|
||||||
(0..=scope.len())
|
|
||||||
.map(|start| NodeId::new(format!("{}{}", scope[start..].concat(), declared.as_str())))
|
|
||||||
.find(|candidate| index.contains_key(candidate))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn number(text: &str) -> Option<f64> {
|
|
||||||
text.trim().parse::<f64>().ok().filter(|value| value.is_finite())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The value one input sends: its draft when it has one of the right kind, else what it is bound to.
|
|
||||||
fn value(tree: &BoundTree, drafts: &Drafts, surface: &str, laid: &NodeId, node: &Node) -> Option<InputValue> {
|
|
||||||
let draft = drafts.get(surface, laid);
|
|
||||||
let bound = |field| tree.value(laid, field);
|
|
||||||
match node {
|
|
||||||
Node::Toggle(_) => match (draft, bound(Field::Checked)) {
|
|
||||||
(Some(InputValue::Bool(held)), _) => Some(InputValue::Bool(held.clone())),
|
|
||||||
(_, Some(Bound::Bool(checked))) => Some(InputValue::Bool(BoolValue { value: *checked })),
|
|
||||||
_ => None,
|
|
||||||
},
|
|
||||||
Node::Slider(_) => match (draft, bound(Field::Value)) {
|
|
||||||
(Some(InputValue::Number(held)), _) => Some(InputValue::Number(held.clone())),
|
|
||||||
(_, Some(Bound::Number(at))) => Some(InputValue::Number(NumberValue { value: *at })),
|
|
||||||
_ => None,
|
|
||||||
},
|
|
||||||
Node::Select(_) => match (draft, bound(Field::Selected)) {
|
|
||||||
(Some(InputValue::Choice(held)), _) => Some(InputValue::Choice(held.clone())),
|
|
||||||
(_, Some(Bound::Text(selected))) => Some(InputValue::Choice(ChoiceValue { value: selected.clone() })),
|
|
||||||
_ => None,
|
|
||||||
},
|
|
||||||
Node::TextInput(input) => {
|
|
||||||
let initial = match bound(Field::Initial) {
|
|
||||||
Some(Bound::Text(text)) => Some(text.as_str()),
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
match input.input_kind {
|
|
||||||
InputKind::Text => match (draft, initial) {
|
|
||||||
(Some(InputValue::Text(held)), _) => Some(InputValue::Text(held.clone())),
|
|
||||||
(_, Some(text)) => Some(InputValue::Text(TextValue { value: text.to_string() })),
|
|
||||||
_ => None,
|
|
||||||
},
|
|
||||||
InputKind::Number => {
|
|
||||||
let typed = match draft {
|
|
||||||
Some(InputValue::Text(held)) => number(&held.value),
|
|
||||||
Some(InputValue::Number(held)) => Some(held.value).filter(|value| value.is_finite()),
|
|
||||||
_ => initial.and_then(number),
|
|
||||||
};
|
|
||||||
typed.map(|value| InputValue::Number(NumberValue { value }))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The captures of `decl`, in declared order, resolved from the scope of the activating node. The
|
|
||||||
/// error is the declared id of the first capture with no value to send.
|
|
||||||
pub(super) fn capture(tree: &BoundTree, drafts: &Drafts, surface: &str, scope: &[String], decl: &CommandDecl) -> Result<Captured, NodeId> {
|
|
||||||
let index = tree.index();
|
|
||||||
let mut captured = Captured { inputs: Vec::new(), held: Vec::new() };
|
|
||||||
for declared in &decl.captures {
|
|
||||||
let laid = laid_id(&index, scope, declared).ok_or_else(|| declared.clone())?;
|
|
||||||
let node = index.get(&laid).ok_or_else(|| declared.clone())?;
|
|
||||||
let value = value(tree, drafts, surface, &laid, node).ok_or_else(|| declared.clone())?;
|
|
||||||
captured.inputs.push(CapturedInput { node: declared.clone(), value });
|
|
||||||
if let Some(draft) = drafts.get(surface, &laid) {
|
|
||||||
captured.held.push((laid, draft.clone()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(captured)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The value a change input takes, or why it takes none. A slider is a range input: a value that is
|
|
||||||
/// not finite is refused, and a finite one outside its range is clamped to it. A select takes only an
|
|
||||||
/// option it declares (bound options included, as bound for this node).
|
|
||||||
pub(super) fn change(tree: &BoundTree, laid: &NodeId, node: &Node, value: &InputValue) -> Result<InputValue, &'static str> {
|
|
||||||
match (node, value) {
|
|
||||||
(Node::Slider(slider), InputValue::Number(at)) => {
|
|
||||||
if !at.value.is_finite() {
|
|
||||||
return Err("the slider value is not a finite number");
|
|
||||||
}
|
|
||||||
Ok(InputValue::Number(NumberValue { value: at.value.max(slider.min).min(slider.max) }))
|
|
||||||
}
|
|
||||||
(Node::Select(_), InputValue::Choice(chosen)) => match tree.value(laid, Field::Options) {
|
|
||||||
Some(Bound::Options(options)) if options.iter().any(|option| option.value == chosen.value) => Ok(value.clone()),
|
|
||||||
_ => Err("the choice names no declared option"),
|
|
||||||
},
|
|
||||||
_ => Ok(value.clone()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,183 +0,0 @@
|
||||||
//! The invocation lifecycle: `Issued -> Pending* -> Completed | Denied | Failed`, with the core-only
|
|
||||||
//! terminal states `Malformed` and `TimedOut`. Terminal is final: a later result is a diagnostic,
|
|
||||||
//! never a state change. Core decides every transition; a provider only offers results.
|
|
||||||
|
|
||||||
use thing_contract::{CommandResult, DatabaseEntry, Outcome};
|
|
||||||
|
|
||||||
use super::{Commands, HostEffect, Live, Mark, State, capture, fault, validate};
|
|
||||||
use crate::bind::BoundTree;
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
use crate::input::Drafts;
|
|
||||||
use crate::port::{Change, Ledger, Record, StatePort};
|
|
||||||
use crate::time::Timestamp;
|
|
||||||
|
|
||||||
/// What one drained change did: the effects for the host to run, and what core says about it.
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq)]
|
|
||||||
pub struct Answered {
|
|
||||||
pub effects: Vec<HostEffect>,
|
|
||||||
pub diagnostics: Vec<Diagnostic>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Commands {
|
|
||||||
/// One drained change. Only a command result is this module's; any other address is not and
|
|
||||||
/// answers empty. A result under no held invocation is `UnknownInvocation`, logged only.
|
|
||||||
/// `trees` finds a surface's bound tree by record key.
|
|
||||||
pub fn apply<'t>(
|
|
||||||
&mut self,
|
|
||||||
change: &Change,
|
|
||||||
now: Timestamp,
|
|
||||||
trees: &dyn Fn(&str) -> Option<&'t BoundTree>,
|
|
||||||
drafts: &mut Drafts,
|
|
||||||
port: &mut dyn StatePort,
|
|
||||||
ledger: &mut Ledger,
|
|
||||||
) -> Answered {
|
|
||||||
let mut answered = Answered::default();
|
|
||||||
let address = match change {
|
|
||||||
Change::Upsert(entry) => &entry.address,
|
|
||||||
Change::Delete(address) => address,
|
|
||||||
Change::Refused(refusal) => &refusal.address,
|
|
||||||
};
|
|
||||||
if address.schema.as_str() != CommandResult::SCHEMA_NAME {
|
|
||||||
return answered;
|
|
||||||
}
|
|
||||||
self.expire(now);
|
|
||||||
let Some(at) = self.live.iter().position(|live| live.interest.matches(address)) else {
|
|
||||||
if !matches!(change, Change::Delete(_)) {
|
|
||||||
answered.diagnostics.push(fault(
|
|
||||||
address.key.as_str(),
|
|
||||||
None,
|
|
||||||
Code::UnknownInvocation,
|
|
||||||
"no invocation of this id is held",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
return answered;
|
|
||||||
};
|
|
||||||
if matches!(change, Change::Delete(_)) {
|
|
||||||
return answered;
|
|
||||||
}
|
|
||||||
let surface = self.live[at].surface.clone();
|
|
||||||
let issuing = self.live[at].issuing.clone();
|
|
||||||
if self.live[at].state.is_terminal() {
|
|
||||||
answered.diagnostics.push(fault(&surface, issuing.as_ref(), Code::ResultAfterTerminal, "the invocation is already terminal"));
|
|
||||||
return answered;
|
|
||||||
}
|
|
||||||
let result = match change {
|
|
||||||
Change::Upsert(entry) => match &entry.record {
|
|
||||||
// One equality catches a body naming another invocation, and a seq that is not the key's.
|
|
||||||
Record::Result(result) if result.record_key() == address.key.as_str() => result,
|
|
||||||
Record::Result(_) => {
|
|
||||||
self.malformed(at, "the result is not the one its key names", now, &mut answered, port, ledger);
|
|
||||||
return answered;
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
self.malformed(at, "the record at a result address is not a result", now, &mut answered, port, ledger);
|
|
||||||
return answered;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
_ => {
|
|
||||||
self.malformed(at, "the result was refused at decode", now, &mut answered, port, ledger);
|
|
||||||
return answered;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let seq = result.seq().get();
|
|
||||||
if seq <= self.live[at].highest {
|
|
||||||
return answered;
|
|
||||||
}
|
|
||||||
self.live[at].highest = seq;
|
|
||||||
match result.outcome() {
|
|
||||||
Outcome::Pending(pending) => {
|
|
||||||
self.live[at].state = State::Pending(pending.message.clone());
|
|
||||||
self.live[at].deadline = now.plus_ms(self.timeout_ms);
|
|
||||||
}
|
|
||||||
Outcome::Completed(completed) => {
|
|
||||||
let effect = match &completed.effect {
|
|
||||||
None => None,
|
|
||||||
Some(effect) => match validate::effect(effect, trees(&surface), &self.live[at]) {
|
|
||||||
Ok(effect) => Some(effect),
|
|
||||||
Err(detail) => {
|
|
||||||
self.malformed(at, &detail, now, &mut answered, port, ledger);
|
|
||||||
return answered;
|
|
||||||
}
|
|
||||||
},
|
|
||||||
};
|
|
||||||
if completed.clear_drafts {
|
|
||||||
drafts.clear_held(&surface, &self.live[at].held);
|
|
||||||
}
|
|
||||||
answered.effects.extend(effect);
|
|
||||||
self.settle(at, State::Completed, None, now, port, ledger);
|
|
||||||
}
|
|
||||||
Outcome::Denied(denied) => {
|
|
||||||
let mut target = issuing.clone();
|
|
||||||
if let Some(declared) = &denied.node {
|
|
||||||
let found = trees(&surface).and_then(|tree| capture::laid_id(&tree.index(), &self.live[at].scope, declared));
|
|
||||||
match found {
|
|
||||||
Some(laid) => target = Some(laid),
|
|
||||||
None => answered.diagnostics.push(fault(
|
|
||||||
&surface,
|
|
||||||
issuing.as_ref(),
|
|
||||||
Code::MalformedResult,
|
|
||||||
"denied node not in the surface",
|
|
||||||
)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self.settle(at, State::Denied, None, now, port, ledger);
|
|
||||||
if let Some(node) = target {
|
|
||||||
self.marks.insert((surface, node), Mark::Denied { reason: denied.reason.clone() });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Outcome::Failed(failed) => {
|
|
||||||
self.settle(at, State::Failed, Some(Mark::Failed { reason: failed.reason.clone() }), now, port, ledger);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
answered
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Within a frame results apply before `tick` (`Core::frame` drains and applies, then ticks), so a
|
|
||||||
/// result queued for the frame its deadline passes wins over the timeout.
|
|
||||||
/// Move every non-terminal invocation whose deadline has come to `TimedOut`. A deadline is
|
|
||||||
/// compared with the time given: a wall clock that went backward delays a timeout, never fires one early.
|
|
||||||
pub fn tick(&mut self, now: Timestamp, port: &mut dyn StatePort, ledger: &mut Ledger) -> Vec<Diagnostic> {
|
|
||||||
self.expire(now);
|
|
||||||
let mut diagnostics = Vec::new();
|
|
||||||
for at in 0..self.live.len() {
|
|
||||||
let live = &self.live[at];
|
|
||||||
if !live.state.is_terminal() && live.deadline <= now {
|
|
||||||
diagnostics.push(fault(&live.surface, live.issuing.as_ref(), Code::InvocationTimedOut, "no result by the deadline"));
|
|
||||||
self.settle(at, State::TimedOut, Some(Mark::TimedOut), now, port, ledger);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
diagnostics
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The earliest deadline of an invocation still waiting; the frame's `next_wake`.
|
|
||||||
pub fn next_deadline(&self) -> Option<Timestamp> {
|
|
||||||
self.live.iter().filter(|live| !live.state.is_terminal()).map(|live: &Live| live.deadline).min()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A result core will not take: the invocation is `Malformed`, and nothing it carried runs.
|
|
||||||
fn malformed(&mut self, at: usize, detail: &str, now: Timestamp, answered: &mut Answered, port: &mut dyn StatePort, ledger: &mut Ledger) {
|
|
||||||
let live = &self.live[at];
|
|
||||||
answered.diagnostics.push(fault(&live.surface, live.issuing.as_ref(), Code::MalformedResult, detail));
|
|
||||||
self.settle(at, State::Malformed, Some(Mark::Malformed), now, port, ledger);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Forget the invocations that went terminal a whole timeout ago: a result after that is for an
|
|
||||||
/// invocation core no longer holds, so the table stays bounded by the work of one timeout. A
|
|
||||||
/// result inside the window is still judged against the invocation (`ResultAfterTerminal`).
|
|
||||||
fn expire(&mut self, now: Timestamp) {
|
|
||||||
let timeout = self.timeout_ms;
|
|
||||||
self.live.retain(|live| live.done.is_none_or(|done| now < done.plus_ms(timeout)));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Enter a terminal state: the interest in results is released in the same call, and the
|
|
||||||
/// issuing node shows the mark.
|
|
||||||
fn settle(&mut self, at: usize, state: State, mark: Option<Mark>, now: Timestamp, port: &mut dyn StatePort, ledger: &mut Ledger) {
|
|
||||||
let live = &mut self.live[at];
|
|
||||||
live.state = state;
|
|
||||||
live.done = Some(now);
|
|
||||||
ledger.release(port, &live.interest);
|
|
||||||
if let (Some(mark), Some(node)) = (mark, &live.issuing) {
|
|
||||||
self.marks.insert((live.surface.clone(), node.clone()), mark);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,494 +0,0 @@
|
||||||
//! Commands: the one owner of invocation minting, the invocation lifecycle and result validation.
|
|
||||||
//! It follows the Resolver and Binder: it is handed what the frame drained and never drains, reads
|
|
||||||
//! no clock (time is a parameter) and awaits nothing. Core writes no record but an invocation, and
|
|
||||||
//! that leaves through `take_outbound`, never through a port.
|
|
||||||
//!
|
|
||||||
//! Every way of minting (a press, a key, a confirmed dialog, a resume after an external step)
|
|
||||||
//! ends in `mint`. A user action mints one id; nothing re-mints.
|
|
||||||
|
|
||||||
mod capture;
|
|
||||||
mod lifecycle;
|
|
||||||
mod validate;
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
use thing_contract::{
|
|
||||||
CapturedInput, CommandDecl, CommandId, CommandInvocation, CommandRef, CommandResult, DatabaseEntry, InputValue, Node, NodeId,
|
|
||||||
ProviderId, RecordPayload, SchemaId, Seq, Version,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::bind::{Bound, BoundTree, Field};
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
use crate::input::Drafts;
|
|
||||||
use crate::port::{IdSource, Interest, Ledger, Prefix, StatePort};
|
|
||||||
use crate::time::Timestamp;
|
|
||||||
|
|
||||||
pub use lifecycle::Answered;
|
|
||||||
|
|
||||||
/// The empty MessagePack array: a payload record with no slots. Thing Script has no payload source yet.
|
|
||||||
const EMPTY_PAYLOAD: [u8; 1] = [0x90];
|
|
||||||
|
|
||||||
/// What the user did to one node.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct Activation {
|
|
||||||
/// The laid id, instance ids included.
|
|
||||||
pub node: NodeId,
|
|
||||||
pub kind: ActivationKind,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub enum ActivationKind {
|
|
||||||
/// A Button or an Overlay's dismissal.
|
|
||||||
Press,
|
|
||||||
/// A Toggle, a Slider or a Select took a value; it is written to Drafts first, then the command fires.
|
|
||||||
Change(InputValue),
|
|
||||||
/// A TextInput's submit.
|
|
||||||
Submit,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What the host runs for a provider's result. Closed.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub enum HostEffect {
|
|
||||||
OpenSurface { key: String },
|
|
||||||
OpenExternal { url: String, resume: Resume },
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The command to run when an external step returns. The host holds it across a navigation (the
|
|
||||||
/// session dies on `location.assign`) and hands it to `Core::resume`. `source` and `items` are the
|
|
||||||
/// invocation's, so a resumed command names the same row.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct Resume {
|
|
||||||
pub surface_key: String,
|
|
||||||
pub command: CommandId,
|
|
||||||
pub source: NodeId,
|
|
||||||
pub items: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Why a node shows a fault: the last terminal answer of an invocation issued from it, until it mints again.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub enum Mark {
|
|
||||||
Denied { reason: String },
|
|
||||||
Failed { reason: String },
|
|
||||||
Malformed,
|
|
||||||
TimedOut,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What render and accessibility read of one node. Derived from the live invocations; nothing is
|
|
||||||
/// stored on a node.
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq)]
|
|
||||||
pub struct NodeState {
|
|
||||||
/// A non-terminal invocation was issued from this node.
|
|
||||||
pub busy: bool,
|
|
||||||
pub mark: Option<Mark>,
|
|
||||||
/// The message of the latest Pending result of a busy node's invocation.
|
|
||||||
pub pending: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq)]
|
|
||||||
pub struct NodeStates {
|
|
||||||
nodes: HashMap<NodeId, NodeState>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl NodeStates {
|
|
||||||
/// The state of a laid node; a node nothing happened to is the default.
|
|
||||||
pub fn get(&self, node: &NodeId) -> NodeState {
|
|
||||||
self.nodes.get(node).cloned().unwrap_or_default()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A command waiting for the user's yes. Its captures are the values at the user's action.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct Confirming {
|
|
||||||
pub surface: String,
|
|
||||||
pub node: NodeId,
|
|
||||||
pub command: CommandId,
|
|
||||||
pub text: String,
|
|
||||||
prepared: Prepared,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Confirming {
|
|
||||||
pub fn captured(&self) -> &[CapturedInput] {
|
|
||||||
&self.prepared.captured
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Everything an invocation is except its id and its time: what a confirm holds until the user answers.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
struct Prepared {
|
|
||||||
surface: String,
|
|
||||||
provider: ProviderId,
|
|
||||||
version: Version,
|
|
||||||
command: CommandId,
|
|
||||||
payload_schema: SchemaId,
|
|
||||||
captured: Vec<CapturedInput>,
|
|
||||||
held: Vec<(NodeId, InputValue)>,
|
|
||||||
source: NodeId,
|
|
||||||
items: Vec<String>,
|
|
||||||
/// The laid node the user acted on; a resume has none.
|
|
||||||
issuing: Option<NodeId>,
|
|
||||||
/// The instance prefixes around the issuing node, innermost first.
|
|
||||||
scope: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An invocation core issued. Terminal ones stay so a late result is judged, not lost.
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
struct Live {
|
|
||||||
surface: String,
|
|
||||||
issuing: Option<NodeId>,
|
|
||||||
state: State,
|
|
||||||
/// The highest result `seq` taken.
|
|
||||||
highest: i32,
|
|
||||||
deadline: Timestamp,
|
|
||||||
/// When it went terminal; `None` while it waits.
|
|
||||||
done: Option<Timestamp>,
|
|
||||||
held: Vec<(NodeId, InputValue)>,
|
|
||||||
scope: Vec<String>,
|
|
||||||
interest: Interest,
|
|
||||||
source: NodeId,
|
|
||||||
items: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
enum State {
|
|
||||||
Issued,
|
|
||||||
Pending(String),
|
|
||||||
Completed,
|
|
||||||
Denied,
|
|
||||||
Failed,
|
|
||||||
Malformed,
|
|
||||||
TimedOut,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl State {
|
|
||||||
fn is_terminal(&self) -> bool {
|
|
||||||
!matches!(self, State::Issued | State::Pending(_))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Commands {
|
|
||||||
client: String,
|
|
||||||
timeout_ms: u32,
|
|
||||||
live: Vec<Live>,
|
|
||||||
marks: HashMap<(String, NodeId), Mark>,
|
|
||||||
confirming: Option<Confirming>,
|
|
||||||
outbound: Vec<CommandInvocation>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn fault(surface: &str, node: Option<&NodeId>, code: Code, detail: impl Into<String>) -> Diagnostic {
|
|
||||||
Diagnostic { code, surface: surface.to_string(), node: node.cloned(), detail: detail.into() }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An activation core did not act on because the caller asked for something invalid; nothing was
|
|
||||||
/// minted and no draft was written. A host treats it as a bug in itself.
|
|
||||||
fn refused(surface: &str, node: &NodeId, detail: &str) -> Diagnostic {
|
|
||||||
fault(surface, Some(node), Code::ActivationRefused, detail)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An otherwise valid activation a user state stopped (a command waits for confirmation, or the control
|
|
||||||
/// is disabled or waits for its result); nothing was minted and no draft was written. A host may show
|
|
||||||
/// or drop it and never treats it as a bug.
|
|
||||||
fn blocked(surface: &str, node: &NodeId, detail: &str) -> Diagnostic {
|
|
||||||
fault(surface, Some(node), Code::ActivationBlocked, detail)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A v4 UUID from 16 bytes: the version and variant bits are core's, so a minted id is always
|
|
||||||
/// UUID-shaped and dot-free (a result key splits at its last dot).
|
|
||||||
fn uuid(ids: &mut dyn IdSource) -> String {
|
|
||||||
let mut bytes = [0u8; 16];
|
|
||||||
ids.fill(&mut bytes);
|
|
||||||
bytes[6] = bytes[6] & 0x0f | 0x40;
|
|
||||||
bytes[8] = bytes[8] & 0x3f | 0x80;
|
|
||||||
let hex: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
|
|
||||||
format!("{}-{}-{}-{}-{}", &hex[0..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..32])
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The key prefix every result of `invocation` shares, derived from the contract's one key
|
|
||||||
/// scheme: a result's key is this followed by its `seq`.
|
|
||||||
fn result_prefix(invocation: &CommandInvocation) -> String {
|
|
||||||
let key = CommandResult::pending(invocation, Seq::FIRST, "").record_key();
|
|
||||||
key[..key.rfind('.').map_or(key.len(), |dot| dot + 1)].to_string()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The command a node fires for an activation, when the node takes that kind of activation.
|
|
||||||
fn command_of<'a>(node: &'a Node, kind: &ActivationKind) -> Option<&'a CommandRef> {
|
|
||||||
match (node, kind) {
|
|
||||||
(Node::Button(n), ActivationKind::Press) => Some(&n.on_activate),
|
|
||||||
(Node::Overlay(n), ActivationKind::Press) => Some(&n.dismiss),
|
|
||||||
(Node::TextInput(n), ActivationKind::Submit) => Some(&n.submit),
|
|
||||||
(Node::Toggle(n), ActivationKind::Change(InputValue::Bool(_))) => Some(&n.on_change),
|
|
||||||
(Node::Slider(n), ActivationKind::Change(InputValue::Number(_))) => Some(&n.commit),
|
|
||||||
(Node::Select(n), ActivationKind::Change(InputValue::Choice(_))) => Some(&n.on_change),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where a command is fired from: the declared id of its source, and the instances around it.
|
|
||||||
struct Origin {
|
|
||||||
issuing: Option<NodeId>,
|
|
||||||
source: NodeId,
|
|
||||||
scope: Vec<String>,
|
|
||||||
items: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Commands {
|
|
||||||
pub fn new(client: impl Into<String>, timeout_ms: u32) -> Self {
|
|
||||||
Self {
|
|
||||||
client: client.into(),
|
|
||||||
timeout_ms,
|
|
||||||
live: Vec::new(),
|
|
||||||
marks: HashMap::new(),
|
|
||||||
confirming: None,
|
|
||||||
outbound: Vec::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The one commit primitive: the user acted on `act.node` of `tree`. Every path calls it. It
|
|
||||||
/// mints one invocation, or nothing. A refusal (a node that is not a command source for this kind, a
|
|
||||||
/// node nobody laid, a change the input does not take) answers with a `Code::ActivationRefused`
|
|
||||||
/// diagnostic, whatever the user is doing; a well-formed activation a user state stops (a command
|
|
||||||
/// waiting on confirmation, a change to a busy control) answers with `Code::ActivationBlocked`. A press
|
|
||||||
/// on a disabled or busy button is neither: the user sees it, so it stays silent.
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
|
||||||
pub fn activate(
|
|
||||||
&mut self,
|
|
||||||
act: Activation,
|
|
||||||
tree: &BoundTree,
|
|
||||||
drafts: &mut Drafts,
|
|
||||||
now: Timestamp,
|
|
||||||
ids: &mut dyn IdSource,
|
|
||||||
port: &mut dyn StatePort,
|
|
||||||
ledger: &mut Ledger,
|
|
||||||
) -> Vec<Diagnostic> {
|
|
||||||
let surface = tree.resolved().document().record_key();
|
|
||||||
let Some(located) = tree.locate(&act.node) else {
|
|
||||||
return vec![refused(&surface, &act.node, "the node is not in the surface")];
|
|
||||||
};
|
|
||||||
// A Param command is the same refusal: resolve leaves none in a tree, so none reaches here.
|
|
||||||
let Some(CommandRef::Id(command)) = command_of(located.node, &act.kind) else {
|
|
||||||
return vec![refused(&surface, &act.node, "the node fires no command for this activation")];
|
|
||||||
};
|
|
||||||
// Caller bugs are told before user states: a malformed activation is a bug whatever the user is doing.
|
|
||||||
let taken = match &act.kind {
|
|
||||||
ActivationKind::Change(value) => match capture::change(tree, &act.node, located.node, value) {
|
|
||||||
Ok(taken) => Some(taken),
|
|
||||||
Err(detail) => return vec![refused(&surface, &act.node, detail)],
|
|
||||||
},
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
// A control that takes no change holds no value the user did not send: the gate is before the draft.
|
|
||||||
let stopped = if taken.is_some() { self.refuses_change(tree, &act.node) } else { self.confirming_refusal(&surface, &act.node) };
|
|
||||||
if let Some(stopped) = stopped {
|
|
||||||
return vec![stopped];
|
|
||||||
}
|
|
||||||
if let Some(taken) = taken {
|
|
||||||
drafts.set(&surface, &act.node, taken);
|
|
||||||
}
|
|
||||||
if self.holds(tree, &act.node) {
|
|
||||||
return Vec::new();
|
|
||||||
}
|
|
||||||
let Some(decl) = tree.resolved().document().commands.iter().find(|decl| decl.id == command.id) else {
|
|
||||||
return vec![fault(&surface, Some(&act.node), Code::UndeclaredCommand, "the command is not declared")];
|
|
||||||
};
|
|
||||||
let origin = Origin {
|
|
||||||
issuing: Some(act.node.clone()),
|
|
||||||
source: located.declared,
|
|
||||||
scope: located.prefixes,
|
|
||||||
items: located.items,
|
|
||||||
};
|
|
||||||
let prepared = match self.prepare(tree, drafts, decl, origin) {
|
|
||||||
Ok(prepared) => prepared,
|
|
||||||
Err(diagnostic) => return vec![diagnostic],
|
|
||||||
};
|
|
||||||
self.begin(prepared, act.node, decl.confirm.as_ref(), now, ids, port, ledger)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Why `node` takes no change now, said as `Code::ActivationBlocked`: a command waits for confirmation,
|
|
||||||
/// or its own invocation waits for a result. A change that is blocked writes no draft, so a busy
|
|
||||||
/// control never holds a value that was not sent. A press on a disabled or busy button stays silent
|
|
||||||
/// (`activate`); a change is an edit the user made and is told.
|
|
||||||
pub(crate) fn refuses_change(&self, tree: &BoundTree, node: &NodeId) -> Option<Diagnostic> {
|
|
||||||
let surface = tree.resolved().document().record_key();
|
|
||||||
if let Some(waiting) = self.confirming_refusal(&surface, node) {
|
|
||||||
return Some(waiting);
|
|
||||||
}
|
|
||||||
self.holds(tree, node).then(|| blocked(&surface, node, "the control is waiting for a result"))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn confirming_refusal(&self, surface: &str, node: &NodeId) -> Option<Diagnostic> {
|
|
||||||
self.confirming.is_some().then(|| blocked(surface, node, "a command is waiting for confirmation"))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether `node` is a disabled Button or has an invocation waiting for its result.
|
|
||||||
fn holds(&self, tree: &BoundTree, node: &NodeId) -> bool {
|
|
||||||
let disabled = tree.value(node, Field::Enabled) == Some(&Bound::Bool(false));
|
|
||||||
disabled || self.busy(&tree.resolved().document().record_key(), node)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Answer the command waiting on confirmation. Accepting mints with the captures taken at the
|
|
||||||
/// user's action; rejecting drops it and draws no id.
|
|
||||||
pub fn confirm(&mut self, accept: bool, now: Timestamp, ids: &mut dyn IdSource, port: &mut dyn StatePort, ledger: &mut Ledger) {
|
|
||||||
if let Some(confirming) = self.confirming.take()
|
|
||||||
&& accept
|
|
||||||
{
|
|
||||||
self.mint(confirming.prepared, now, ids, port, ledger);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn confirming(&self) -> Option<&Confirming> {
|
|
||||||
self.confirming.as_ref()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Run the command an external step named, as the invocation that asked for it: its declared
|
|
||||||
/// captures, its source and items, no issuing node (nothing is marked busy).
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
|
||||||
pub fn resume(
|
|
||||||
&mut self,
|
|
||||||
resume: &Resume,
|
|
||||||
tree: &BoundTree,
|
|
||||||
drafts: &Drafts,
|
|
||||||
now: Timestamp,
|
|
||||||
ids: &mut dyn IdSource,
|
|
||||||
port: &mut dyn StatePort,
|
|
||||||
ledger: &mut Ledger,
|
|
||||||
) -> Vec<Diagnostic> {
|
|
||||||
let surface = tree.resolved().document().record_key();
|
|
||||||
let decl = tree.resolved().document().commands.iter().find(|decl| decl.id == resume.command);
|
|
||||||
let (Some(decl), true) = (decl, surface == resume.surface_key) else {
|
|
||||||
return vec![fault(&surface, None, Code::UndeclaredCommand, "the command to resume is not declared at the held version")];
|
|
||||||
};
|
|
||||||
let scope = tree.locate_source(&resume.source, &resume.items).map(|located| located.prefixes).unwrap_or_default();
|
|
||||||
let origin = Origin { issuing: None, source: resume.source.clone(), scope, items: resume.items.clone() };
|
|
||||||
match self.prepare(tree, drafts, decl, origin) {
|
|
||||||
Ok(prepared) => self.begin(prepared, resume.source.clone(), decl.confirm.as_ref(), now, ids, port, ledger),
|
|
||||||
Err(diagnostic) => vec![diagnostic],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The invocations minted since the last call, in order.
|
|
||||||
pub fn take_outbound(&mut self) -> Vec<CommandInvocation> {
|
|
||||||
std::mem::take(&mut self.outbound)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What render and accessibility read for `surface`.
|
|
||||||
pub fn view(&self, surface: &str) -> NodeStates {
|
|
||||||
let mut nodes: HashMap<NodeId, NodeState> = HashMap::new();
|
|
||||||
for ((held, node), mark) in &self.marks {
|
|
||||||
if held == surface {
|
|
||||||
nodes.entry(node.clone()).or_default().mark = Some(mark.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for live in self.live.iter().filter(|live| live.surface == surface && !live.state.is_terminal()) {
|
|
||||||
if let Some(node) = &live.issuing {
|
|
||||||
let state = nodes.entry(node.clone()).or_default();
|
|
||||||
state.busy = true;
|
|
||||||
if let State::Pending(message) = &live.state {
|
|
||||||
state.pending = Some(message.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
NodeStates { nodes }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The surface is no longer shown: its invocations leave the table with their interests, its
|
|
||||||
/// marks go and a confirmation waiting on it is dropped.
|
|
||||||
pub fn forget(&mut self, surface: &str, port: &mut dyn StatePort, ledger: &mut Ledger) {
|
|
||||||
for live in self.live.iter().filter(|live| live.surface == surface && !live.state.is_terminal()) {
|
|
||||||
ledger.release(port, &live.interest);
|
|
||||||
}
|
|
||||||
self.live.retain(|live| live.surface != surface);
|
|
||||||
self.marks.retain(|(held, _), _| held != surface);
|
|
||||||
if self.confirming.as_ref().is_some_and(|confirming| confirming.surface == surface) {
|
|
||||||
self.confirming = None;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn busy(&self, surface: &str, node: &NodeId) -> bool {
|
|
||||||
self.live.iter().any(|live| !live.state.is_terminal() && live.surface == surface && live.issuing.as_ref() == Some(node))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn prepare(&self, tree: &BoundTree, drafts: &Drafts, decl: &CommandDecl, origin: Origin) -> Result<Prepared, Diagnostic> {
|
|
||||||
let document = tree.resolved().document();
|
|
||||||
let surface = document.record_key();
|
|
||||||
let captured = capture::capture(tree, drafts, &surface, &origin.scope, decl).map_err(|node| {
|
|
||||||
fault(&surface, Some(&node), Code::CaptureUnavailable, "the captured input has no value to send")
|
|
||||||
})?;
|
|
||||||
Ok(Prepared {
|
|
||||||
surface,
|
|
||||||
provider: document.provider_id.clone(),
|
|
||||||
version: document.version,
|
|
||||||
command: decl.id.clone(),
|
|
||||||
payload_schema: decl.payload_schema.clone(),
|
|
||||||
captured: captured.inputs,
|
|
||||||
held: captured.held,
|
|
||||||
source: origin.source,
|
|
||||||
items: origin.items,
|
|
||||||
issuing: origin.issuing,
|
|
||||||
scope: origin.scope,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where every way of acting on a command meets its confirmation: a command that asks waits for the
|
|
||||||
/// user's yes, holding the captures it was prepared with; any other mints. One command waits at a time.
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
|
||||||
fn begin(
|
|
||||||
&mut self,
|
|
||||||
prepared: Prepared,
|
|
||||||
node: NodeId,
|
|
||||||
confirm: Option<&String>,
|
|
||||||
now: Timestamp,
|
|
||||||
ids: &mut dyn IdSource,
|
|
||||||
port: &mut dyn StatePort,
|
|
||||||
ledger: &mut Ledger,
|
|
||||||
) -> Vec<Diagnostic> {
|
|
||||||
let Some(text) = confirm else {
|
|
||||||
self.mint(prepared, now, ids, port, ledger);
|
|
||||||
return Vec::new();
|
|
||||||
};
|
|
||||||
if self.confirming.is_some() {
|
|
||||||
return vec![blocked(&prepared.surface, &node, "another command is waiting for confirmation")];
|
|
||||||
}
|
|
||||||
self.confirming = Some(Confirming { surface: prepared.surface.clone(), node, command: prepared.command.clone(), text: text.clone(), prepared });
|
|
||||||
Vec::new()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The one mint: draw one id, hold the interest in its results before the host can send, and
|
|
||||||
/// queue the invocation.
|
|
||||||
fn mint(&mut self, prepared: Prepared, now: Timestamp, ids: &mut dyn IdSource, port: &mut dyn StatePort, ledger: &mut Ledger) {
|
|
||||||
let invocation = CommandInvocation {
|
|
||||||
invocation_id: uuid(ids),
|
|
||||||
surface_key: prepared.surface.clone(),
|
|
||||||
surface_version: prepared.version,
|
|
||||||
command: prepared.command,
|
|
||||||
payload: RecordPayload { schema: prepared.payload_schema, bytes: EMPTY_PAYLOAD.to_vec() },
|
|
||||||
captured: prepared.captured,
|
|
||||||
client: self.client.clone(),
|
|
||||||
issued_at: now.rfc3339(),
|
|
||||||
delegation: None,
|
|
||||||
source: prepared.source.clone(),
|
|
||||||
items: prepared.items.clone(),
|
|
||||||
};
|
|
||||||
let interest = Interest::Prefix(Prefix {
|
|
||||||
provider: prepared.provider,
|
|
||||||
schema: SchemaId::new(CommandResult::SCHEMA_NAME),
|
|
||||||
key_prefix: result_prefix(&invocation),
|
|
||||||
});
|
|
||||||
ledger.hold(port, &interest);
|
|
||||||
if let Some(node) = &prepared.issuing {
|
|
||||||
self.marks.remove(&(prepared.surface.clone(), node.clone()));
|
|
||||||
}
|
|
||||||
self.live.push(Live {
|
|
||||||
surface: prepared.surface,
|
|
||||||
issuing: prepared.issuing,
|
|
||||||
state: State::Issued,
|
|
||||||
highest: 0,
|
|
||||||
deadline: now.plus_ms(self.timeout_ms),
|
|
||||||
done: None,
|
|
||||||
held: prepared.held,
|
|
||||||
scope: prepared.scope,
|
|
||||||
interest,
|
|
||||||
source: prepared.source,
|
|
||||||
items: prepared.items,
|
|
||||||
});
|
|
||||||
self.outbound.push(invocation);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,58 +0,0 @@
|
||||||
//! What core will run for a provider's result: the closed effects, judged before any is emitted.
|
|
||||||
//! A provider decides what to ask; core decides whether it is allowed.
|
|
||||||
|
|
||||||
use thing_contract::{CommandId, CommandRef, Effect};
|
|
||||||
|
|
||||||
use super::{HostEffect, Live, Resume};
|
|
||||||
use crate::bind::BoundTree;
|
|
||||||
|
|
||||||
/// Whether `url` is absolute with the scheme http or https (ASCII case-insensitive) and a host.
|
|
||||||
fn web_url(url: &str) -> bool {
|
|
||||||
if url.chars().any(|c| c.is_control() || c.is_whitespace()) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
let Some((scheme, rest)) = url.split_once("://") else { return false };
|
|
||||||
(scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https"))
|
|
||||||
&& !rest.starts_with(['/', '?', '#'])
|
|
||||||
&& !rest.is_empty()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The effect as data for the host, or why core refuses it. `tree` is the invocation's surface as
|
|
||||||
/// held now: a resume names a command that surface declares.
|
|
||||||
pub(super) fn effect(effect: &Effect, tree: Option<&BoundTree>, live: &Live) -> Result<HostEffect, String> {
|
|
||||||
match effect {
|
|
||||||
Effect::OpenSurface(open) => {
|
|
||||||
if open.key.starts_with("thing:surface:") {
|
|
||||||
Ok(HostEffect::OpenSurface { key: open.key.clone() })
|
|
||||||
} else {
|
|
||||||
Err("OpenSurface names a key that is not a surface".into())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Effect::OpenExternal(open) => {
|
|
||||||
if !web_url(&open.url) {
|
|
||||||
return Err("OpenExternal names a url that is not absolute http or https".into());
|
|
||||||
}
|
|
||||||
let CommandRef::Id(resume) = &open.resume else {
|
|
||||||
return Err("OpenExternal resumes through a parameter".into());
|
|
||||||
};
|
|
||||||
let declared = tree.is_some_and(|tree| declares(tree, &resume.id));
|
|
||||||
if !declared {
|
|
||||||
return Err("OpenExternal resumes a command the surface does not declare".into());
|
|
||||||
}
|
|
||||||
Ok(HostEffect::OpenExternal {
|
|
||||||
url: open.url.clone(),
|
|
||||||
resume: Resume {
|
|
||||||
surface_key: live.surface.clone(),
|
|
||||||
command: resume.id.clone(),
|
|
||||||
source: live.source.clone(),
|
|
||||||
items: live.items.clone(),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn declares(tree: &BoundTree, command: &CommandId) -> bool {
|
|
||||||
tree.resolved().document().commands.iter().any(|decl| &decl.id == command)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
@ -1,89 +0,0 @@
|
||||||
//! What core says about a document it could not take whole. The code set is closed: a later
|
|
||||||
//! cut adds its codes as reviewed changes, never as free strings.
|
|
||||||
|
|
||||||
use thing_contract::NodeId;
|
|
||||||
|
|
||||||
/// Why a document, or one node of it, was not taken as authored.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
|
||||||
pub enum Code {
|
|
||||||
/// The port refused the composition's bytes. A refusal is never absence.
|
|
||||||
DecodeRefused,
|
|
||||||
/// No composition is published at the named address.
|
|
||||||
UnresolvedUse,
|
|
||||||
/// A composition that uses itself through others, or a chain deeper than the limit.
|
|
||||||
CompositionCycle,
|
|
||||||
/// An argument, a body or a composition record that does not fit its Use.
|
|
||||||
CompositionInvalid,
|
|
||||||
/// A command no surface declaration names.
|
|
||||||
UndeclaredCommand,
|
|
||||||
/// Two nodes of the expanded tree share an id.
|
|
||||||
DuplicateNodeId,
|
|
||||||
/// A Param or a Slot outside any composition.
|
|
||||||
UnboundParam,
|
|
||||||
/// The expanded tree has too many nodes or is deeper than the depth rule.
|
|
||||||
ExpansionLimit,
|
|
||||||
/// The input nests deeper than the expander can recurse. A stack bound, not the depth rule: the depth
|
|
||||||
/// rule is judged on the finished tree and reports ExpansionLimit.
|
|
||||||
TooDeepToResolve,
|
|
||||||
/// A state record held under another schema than the Bind names.
|
|
||||||
BindSchemaMismatch,
|
|
||||||
/// An Image names a catalog or an asset the catalog does not hold.
|
|
||||||
AssetMissing,
|
|
||||||
/// A member path names a member the value does not have.
|
|
||||||
BindMemberMissing,
|
|
||||||
/// A value of another type than its site takes; no value is coerced.
|
|
||||||
BindTypeMismatch,
|
|
||||||
/// Two items of one Repeat share a key.
|
|
||||||
RepeatKeyDuplicate,
|
|
||||||
/// A surface offered at a version at or below one already offered; the held tree stays.
|
|
||||||
StaleVersionIgnored,
|
|
||||||
/// A style slot holding a value its CSS counterpart forbids; the slot took its initial value.
|
|
||||||
StyleValueInvalid,
|
|
||||||
/// A laid node reaches past the precision bound: the layout is refused, never rounded.
|
|
||||||
LayoutOutOfRange,
|
|
||||||
/// An Overlay anchored to a node that is not laid (hidden or absent); it was placed against the viewport.
|
|
||||||
OverlayAnchorMissing,
|
|
||||||
/// A colour or text token the theme does not hold; it drew as the fallback colour.
|
|
||||||
ThemeTokenUnknown,
|
|
||||||
/// A result that could not be taken: refused by decode, not a result, filed under another key than its
|
|
||||||
/// own, or carrying an effect core will not run. The invocation is Malformed.
|
|
||||||
MalformedResult,
|
|
||||||
/// A result under the result key space for an invocation core does not hold.
|
|
||||||
UnknownInvocation,
|
|
||||||
/// A result for an invocation already terminal; the state does not change.
|
|
||||||
ResultAfterTerminal,
|
|
||||||
/// An invocation with no result by its deadline; it is TimedOut.
|
|
||||||
InvocationTimedOut,
|
|
||||||
/// A capture whose input has no value to send (a bound error, absent, or a number that does not parse);
|
|
||||||
/// nothing was minted.
|
|
||||||
CaptureUnavailable,
|
|
||||||
/// A command capture naming no node, or a node that holds no input value.
|
|
||||||
CaptureUndeclared,
|
|
||||||
/// An activation core refused to act on because the caller was wrong: a kind the node does not take, a
|
|
||||||
/// node nobody laid, a change value outside what the input allows, no surface shown, or a resume that
|
|
||||||
/// can no longer run. Nothing was minted; the detail says which. A host logs it as a caller bug, as
|
|
||||||
/// it logs the other caller bugs of the activation path: `UndeclaredCommand` and `CaptureUnavailable`.
|
|
||||||
ActivationRefused,
|
|
||||||
/// A well-formed activation a user state stopped: a command waits for confirmation (this one or
|
|
||||||
/// another), or a change reached a control that waits for its own result. Nothing was minted and no
|
|
||||||
/// draft was written; a host may show or drop it, and it is never a bug. A press on a disabled or busy
|
|
||||||
/// button says nothing at all.
|
|
||||||
ActivationBlocked,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Code {
|
|
||||||
/// Whether the fault leaves no tree (the whole document is refused) or only a placeholder.
|
|
||||||
pub fn refuses_document(self) -> bool {
|
|
||||||
matches!(self, Code::UndeclaredCommand | Code::DuplicateNodeId | Code::UnboundParam | Code::ExpansionLimit | Code::TooDeepToResolve | Code::CaptureUndeclared)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One fault. `detail` names the fault and never carries a state value.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub struct Diagnostic {
|
|
||||||
pub code: Code,
|
|
||||||
/// The record key of the surface the fault is in.
|
|
||||||
pub surface: String,
|
|
||||||
pub node: Option<NodeId>,
|
|
||||||
pub detail: String,
|
|
||||||
}
|
|
||||||
|
|
@ -1,314 +0,0 @@
|
||||||
//! The frame entry: one `Core::frame` call per frame the host makes drains the port, resolves,
|
|
||||||
//! binds, lays out and renders. Core owns the pipeline order and is the only caller of
|
|
||||||
//! `StatePort::drain`; it reads no clock, sleeps nowhere and never awaits. Later cuts extend
|
|
||||||
//! `frame` in place with their own step; there is no second entry.
|
|
||||||
|
|
||||||
use thing_contract::{CommandInvocation, DatabaseEntry, ProviderId, RecordKey, SchemaId, SurfaceDocument};
|
|
||||||
|
|
||||||
use std::collections::HashSet;
|
|
||||||
|
|
||||||
use crate::bind::Binder;
|
|
||||||
use crate::command::{Activation, Commands, Confirming, HostEffect, Resume};
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
use crate::input::{Drafts, Input, InputEvent, Owners, Seen};
|
|
||||||
use crate::layout::{LaidTree, LayoutError, LayoutFrame, Measure, Metrics, layout};
|
|
||||||
use crate::port::{Address, Change, IdSource, Interest, Ledger, Lookup, StatePort};
|
|
||||||
use crate::render::{RenderCommand, RenderInput, Rendered, ScrollOffsets, Session, render};
|
|
||||||
use crate::resolve::{Limits, Resolver};
|
|
||||||
use crate::theme::Theme;
|
|
||||||
use crate::time::Timestamp;
|
|
||||||
|
|
||||||
/// What a core is built with. `metrics` is the mode of the one `Measure` core owns.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct Config {
|
|
||||||
pub limits: Limits,
|
|
||||||
pub metrics: Metrics,
|
|
||||||
/// How long an invocation waits for a result, and for the next one after a Pending (a heartbeat).
|
|
||||||
/// A guess, to be measured (build-spec O5).
|
|
||||||
pub invocation_timeout_ms: u32,
|
|
||||||
/// The kind of host core runs in (`renderer.web`, `renderer.tui`), written to every invocation. It
|
|
||||||
/// is never a caller identity: core has no identity to write, the transport sets it.
|
|
||||||
pub client: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Config {
|
|
||||||
pub fn new(metrics: Metrics, client: impl Into<String>) -> Self {
|
|
||||||
Self { limits: Limits::default(), metrics, invocation_timeout_ms: 15_000, client: client.into() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The ports lent to one frame. The host owns its state port and changes it between frames;
|
|
||||||
/// it lends the same port every frame, because core's `Ledger` counts the subscriptions it made
|
|
||||||
/// on that port.
|
|
||||||
pub struct Ports<'a> {
|
|
||||||
pub state: &'a mut dyn StatePort,
|
|
||||||
pub ids: &'a mut dyn IdSource,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What the host tells core each frame. `viewport` is the one writer of size: logical px
|
|
||||||
/// (`Metrics::Pixels`) or cells (`Metrics::Cells`), the space `LayoutFrame` takes; a resize is
|
|
||||||
/// the next frame's viewport.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct FrameInput {
|
|
||||||
pub now: Timestamp,
|
|
||||||
pub viewport: (f32, f32),
|
|
||||||
pub scale: f32,
|
|
||||||
pub events: Vec<InputEvent>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What a frame hands back. Later cuts add fields; hosts keep compiling.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
#[non_exhaustive]
|
|
||||||
pub struct FrameOutput {
|
|
||||||
pub commands: Vec<RenderCommand>,
|
|
||||||
pub diagnostics: Vec<Diagnostic>,
|
|
||||||
/// When the host should call `frame` again with nothing else to say; `None` while nothing in
|
|
||||||
/// core depends on time.
|
|
||||||
pub next_wake: Option<Timestamp>,
|
|
||||||
/// The invocations minted since the last frame, in order: core's only outbound write.
|
|
||||||
pub outbound: Vec<CommandInvocation>,
|
|
||||||
/// What the host runs for the results taken this frame.
|
|
||||||
pub effects: Vec<HostEffect>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Core {
|
|
||||||
metrics: Metrics,
|
|
||||||
measure: Box<dyn Measure>,
|
|
||||||
resolver: Resolver,
|
|
||||||
binder: Binder,
|
|
||||||
ledger: Ledger,
|
|
||||||
scroll: ScrollOffsets,
|
|
||||||
theme: Theme,
|
|
||||||
commands: Commands,
|
|
||||||
drafts: Drafts,
|
|
||||||
/// The pointer's press in progress.
|
|
||||||
input: Input,
|
|
||||||
/// What activations said since the last frame; the frame's diagnostics carry it out.
|
|
||||||
notes: Vec<Diagnostic>,
|
|
||||||
/// Resumes whose surface had not bound when the host handed them over; each runs at that surface's
|
|
||||||
/// first bind, or is dropped when the surface is left first.
|
|
||||||
held: Vec<Resume>,
|
|
||||||
/// The surface `show` named, and the one whose interest and trees are held.
|
|
||||||
wanted: Option<Address>,
|
|
||||||
shown: Option<Address>,
|
|
||||||
/// The last good frame: what the user saw, which hit-test reads.
|
|
||||||
last: Option<(LaidTree, Rendered)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Core {
|
|
||||||
pub fn new(config: Config, measure: Box<dyn Measure>) -> Self {
|
|
||||||
Self {
|
|
||||||
metrics: config.metrics,
|
|
||||||
measure,
|
|
||||||
resolver: Resolver::new(config.limits.clone()),
|
|
||||||
binder: Binder::new(config.limits),
|
|
||||||
ledger: Ledger::new(),
|
|
||||||
scroll: ScrollOffsets::default(),
|
|
||||||
theme: Theme::std(),
|
|
||||||
commands: Commands::new(config.client, config.invocation_timeout_ms),
|
|
||||||
drafts: Drafts::new(),
|
|
||||||
input: Input::new(),
|
|
||||||
notes: Vec::new(),
|
|
||||||
held: Vec::new(),
|
|
||||||
wanted: None,
|
|
||||||
shown: None,
|
|
||||||
last: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Name the one surface displayed. It takes effect at the next frame.
|
|
||||||
pub fn show(&mut self, provider: ProviderId, key: RecordKey) {
|
|
||||||
self.wanted = Some(Address { provider, schema: SchemaId::new(SurfaceDocument::SCHEMA_NAME), key });
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn frame(&mut self, input: FrameInput, ports: Ports<'_>) -> FrameOutput {
|
|
||||||
let FrameInput { now, viewport, scale, events } = input;
|
|
||||||
let port = ports.state;
|
|
||||||
// Input is judged entirely against the frame the user saw: its geometry and the values bound
|
|
||||||
// into it. Nothing of this frame (the surface it switches to, the provider updates it drains,
|
|
||||||
// the tree it binds) is in place yet, so no event reads a world the user did not look at.
|
|
||||||
let routed = self.route(&events, scale, now, ports.ids, port);
|
|
||||||
let mut changes = Vec::new();
|
|
||||||
if self.wanted != self.shown {
|
|
||||||
self.switch(port, &mut changes);
|
|
||||||
}
|
|
||||||
changes.extend(port.drain());
|
|
||||||
|
|
||||||
let mut diagnostics = std::mem::take(&mut self.notes);
|
|
||||||
diagnostics.extend(routed);
|
|
||||||
let mut effects = Vec::new();
|
|
||||||
let mut rebound = false;
|
|
||||||
for change in &changes {
|
|
||||||
let intake = self.resolver.apply(change, port, &mut self.ledger);
|
|
||||||
diagnostics.extend(intake.diagnostics);
|
|
||||||
for (key, replaced) in intake.changed {
|
|
||||||
if replaced {
|
|
||||||
if let Some(tree) = self.resolver.tree(&key).cloned() {
|
|
||||||
let bound = self.binder.bind(tree, port, &mut self.ledger);
|
|
||||||
rebound |= !bound.dirty.is_empty();
|
|
||||||
diagnostics.extend(bound.diagnostics);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
self.binder.forget(&key, port, &mut self.ledger);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let applied = self.binder.apply(change, port, &mut self.ledger);
|
|
||||||
rebound |= !applied.dirty.is_empty();
|
|
||||||
diagnostics.extend(applied.diagnostics);
|
|
||||||
let binder = &self.binder;
|
|
||||||
let answered = self.commands.apply(change, now, &|key| binder.tree(key), &mut self.drafts, port, &mut self.ledger);
|
|
||||||
diagnostics.extend(answered.diagnostics);
|
|
||||||
effects.extend(answered.effects);
|
|
||||||
}
|
|
||||||
if rebound {
|
|
||||||
self.retain_drafts();
|
|
||||||
}
|
|
||||||
for resume in std::mem::take(&mut self.held) {
|
|
||||||
match self.binder.tree(&resume.surface_key) {
|
|
||||||
Some(tree) => {
|
|
||||||
let said = self.commands.resume(&resume, tree, &self.drafts, now, ports.ids, port, &mut self.ledger);
|
|
||||||
diagnostics.extend(said);
|
|
||||||
}
|
|
||||||
None => self.held.push(resume),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Results of this frame are applied above, before the deadline is judged: a late result that was
|
|
||||||
// already queued wins over the timeout.
|
|
||||||
diagnostics.extend(self.commands.tick(now, port, &mut self.ledger));
|
|
||||||
|
|
||||||
let commands = self.draw(viewport, scale, &mut diagnostics);
|
|
||||||
FrameOutput {
|
|
||||||
commands,
|
|
||||||
diagnostics,
|
|
||||||
next_wake: self.commands.next_deadline(),
|
|
||||||
outbound: self.commands.take_outbound(),
|
|
||||||
effects,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The host's semantic activation: the user, or an accessibility action or an automation acting for
|
|
||||||
/// them, activated a node of the shown surface. It is the one primitive every input path ends in (pointer and
|
|
||||||
/// keyboard routes arrive here too). The invocation it mints is in the next
|
|
||||||
/// frame's `outbound`; a refusal (see `Commands::activate`) is said in that frame's `diagnostics`.
|
|
||||||
pub fn activate(&mut self, act: Activation, now: Timestamp, ports: Ports<'_>) {
|
|
||||||
let Some(tree) = self.shown.as_ref().and_then(|shown| self.binder.tree(shown.key.as_str())) else {
|
|
||||||
let node = Some(act.node);
|
|
||||||
self.notes.push(Diagnostic { code: Code::ActivationRefused, surface: String::new(), node, detail: "no surface is shown".into() });
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let said = self.commands.activate(act, tree, &mut self.drafts, now, ports.ids, ports.state, &mut self.ledger);
|
|
||||||
self.notes.extend(said);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Answer the command waiting on confirmation (`confirming`). The host shows the question and calls
|
|
||||||
/// this with the user's answer; accepting mints with the captures taken at the activation.
|
|
||||||
pub fn confirm(&mut self, accept: bool, now: Timestamp, ports: Ports<'_>) {
|
|
||||||
self.commands.confirm(accept, now, ports.ids, ports.state, &mut self.ledger);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The command waiting for the user's yes or no, for the host to ask.
|
|
||||||
pub fn confirming(&self) -> Option<&Confirming> {
|
|
||||||
self.commands.confirming()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Run the command an `OpenExternal` effect named, once the external step has returned. The host
|
|
||||||
/// holds the `Resume` across the navigation and hands it back here; the command is minted, or asks
|
|
||||||
/// for confirmation, like an activation. A resume handed over before its surface has bound is held and
|
|
||||||
/// runs at the first bind; one whose surface is left first is dropped and said. Any other refusal is
|
|
||||||
/// said in the next frame's `diagnostics`.
|
|
||||||
pub fn resume(&mut self, resume: &Resume, now: Timestamp, ports: Ports<'_>) {
|
|
||||||
let Some(tree) = self.binder.tree(&resume.surface_key) else {
|
|
||||||
self.held.push(resume.clone());
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
let said = self.commands.resume(resume, tree, &self.drafts, now, ports.ids, ports.state, &mut self.ledger);
|
|
||||||
self.notes.extend(said);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn route(&mut self, events: &[InputEvent], scale: f32, now: Timestamp, ids: &mut dyn IdSource, port: &mut dyn StatePort) -> Vec<Diagnostic> {
|
|
||||||
let mut said = Vec::new();
|
|
||||||
let (Some(shown), Some((laid, rendered))) = (&self.shown, &self.last) else { return said };
|
|
||||||
let Some(tree) = self.binder.tree(shown.key.as_str()) else { return said };
|
|
||||||
let line = self.theme.text.get("body").or_else(|| self.theme.text.get("thing.text")).map_or(16.0, |style| style.size);
|
|
||||||
let seen = Seen { rendered, laid, tree, metrics: self.metrics, scale, line };
|
|
||||||
let mut owners = Owners { commands: &mut self.commands, drafts: &mut self.drafts, scroll: &mut self.scroll, ids, port, ledger: &mut self.ledger };
|
|
||||||
for event in events {
|
|
||||||
said.extend(self.input.event(event, &seen, &mut owners, now));
|
|
||||||
}
|
|
||||||
said
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Drop the drafts of nodes the shown surface no longer has.
|
|
||||||
fn retain_drafts(&mut self) {
|
|
||||||
let Some(shown) = &self.shown else { return };
|
|
||||||
let key = shown.key.as_str();
|
|
||||||
let live: HashSet<_> = match self.binder.tree(key) {
|
|
||||||
Some(tree) => tree.index().keys().map(|id| (*id).clone()).collect(),
|
|
||||||
None => HashSet::new(),
|
|
||||||
};
|
|
||||||
self.drafts.retain(key, &live);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Leave the surface shown and take the one wanted: the interest is held before the one read,
|
|
||||||
/// and what the read finds enters as a change like any republish.
|
|
||||||
fn switch(&mut self, port: &mut dyn StatePort, changes: &mut Vec<Change>) {
|
|
||||||
// A resume is for the surface it names: leaving for another one forgets it.
|
|
||||||
let wanted = self.wanted.as_ref().map(|address| address.key.as_str().to_string());
|
|
||||||
for resume in std::mem::take(&mut self.held) {
|
|
||||||
if wanted.as_deref() == Some(resume.surface_key.as_str()) {
|
|
||||||
self.held.push(resume);
|
|
||||||
} else {
|
|
||||||
let detail = "the surface was left before it bound; the resume is dropped";
|
|
||||||
self.notes.push(Diagnostic { code: Code::ActivationRefused, surface: resume.surface_key, node: Some(resume.source), detail: detail.into() });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if let Some(old) = self.shown.take() {
|
|
||||||
self.input.cancel(old.key.as_str(), &mut self.drafts);
|
|
||||||
self.resolver.forget(old.key.as_str(), port, &mut self.ledger);
|
|
||||||
self.binder.forget(old.key.as_str(), port, &mut self.ledger);
|
|
||||||
self.commands.forget(old.key.as_str(), port, &mut self.ledger);
|
|
||||||
self.ledger.release(port, &Interest::Record(old));
|
|
||||||
self.scroll = ScrollOffsets::default();
|
|
||||||
self.last = None;
|
|
||||||
}
|
|
||||||
if let Some(new) = self.wanted.clone() {
|
|
||||||
self.ledger.hold(port, &Interest::Record(new.clone()));
|
|
||||||
match port.read(&new) {
|
|
||||||
Lookup::Present(entry) => changes.push(Change::Upsert(entry)),
|
|
||||||
Lookup::Refused(refusal) => changes.push(Change::Refused(refusal)),
|
|
||||||
Lookup::Absent => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
self.shown = self.wanted.clone();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn draw(&mut self, viewport: (f32, f32), scale: f32, diagnostics: &mut Vec<Diagnostic>) -> Vec<RenderCommand> {
|
|
||||||
let Some(address) = &self.shown else {
|
|
||||||
self.last = None;
|
|
||||||
return Vec::new();
|
|
||||||
};
|
|
||||||
let Some(tree) = self.binder.tree(address.key.as_str()) else {
|
|
||||||
self.last = None;
|
|
||||||
return Vec::new();
|
|
||||||
};
|
|
||||||
let frame = LayoutFrame { viewport, scale, metrics: self.metrics };
|
|
||||||
match layout(tree, &frame, self.measure.as_mut()) {
|
|
||||||
Ok(laid) => {
|
|
||||||
let states = self.commands.view(address.key.as_str());
|
|
||||||
let session = Session::new(&self.drafts, &states);
|
|
||||||
let input = RenderInput { scale, metrics: self.metrics, viewport, scroll: &self.scroll, theme: &self.theme, session };
|
|
||||||
let rendered = render(tree, &laid, &input, self.measure.as_mut());
|
|
||||||
diagnostics.extend(rendered.diagnostics.iter().cloned());
|
|
||||||
let commands = rendered.commands.clone();
|
|
||||||
self.last = Some((laid, rendered));
|
|
||||||
commands
|
|
||||||
}
|
|
||||||
Err(LayoutError::OutOfRange(diagnostic)) => {
|
|
||||||
diagnostics.push(diagnostic);
|
|
||||||
self.last.as_ref().map(|(_, rendered)| rendered.commands.clone()).unwrap_or_default()
|
|
||||||
}
|
|
||||||
// The host's room, not a document fault: nothing is drawn and the last good frame stays.
|
|
||||||
Err(LayoutError::Frame(_)) => Vec::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,82 +0,0 @@
|
||||||
//! Drafts: the one owner of every input node's uncommitted value, keyed (surface key, laid node id).
|
|
||||||
//! A value enters when the user changes an input and leaves when a result clears it or a republish
|
|
||||||
//! removes its node. Nothing else in core, and no host, keeps a second copy.
|
|
||||||
|
|
||||||
use std::borrow::Cow;
|
|
||||||
use std::collections::{HashMap, HashSet};
|
|
||||||
|
|
||||||
use thing_contract::{InputValue, NodeId};
|
|
||||||
|
|
||||||
use crate::bind::{Bound, BoundTree, Field};
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq)]
|
|
||||||
pub struct Drafts {
|
|
||||||
values: HashMap<(String, NodeId), InputValue>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Drafts {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self::default()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set(&mut self, surface: &str, node: &NodeId, value: InputValue) {
|
|
||||||
self.values.insert((surface.to_string(), node.clone()), value);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get(&self, surface: &str, node: &NodeId) -> Option<&InputValue> {
|
|
||||||
self.values.get(&(surface.to_string(), node.clone()))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Put `node`'s draft back to what it was before a press wrote it: `None` leaves it with none.
|
|
||||||
pub fn restore(&mut self, surface: &str, node: &NodeId, prior: Option<InputValue>) {
|
|
||||||
let key = (surface.to_string(), node.clone());
|
|
||||||
match prior {
|
|
||||||
Some(value) => self.values.insert(key, value),
|
|
||||||
None => self.values.remove(&key),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Drop each draft in `held` that the table still holds with that value. A draft edited since it
|
|
||||||
/// was held is newer than what was sent, and stays; a node with no draft is untouched.
|
|
||||||
pub fn clear_held(&mut self, surface: &str, held: &[(NodeId, InputValue)]) {
|
|
||||||
for (node, value) in held {
|
|
||||||
let key = (surface.to_string(), node.clone());
|
|
||||||
if self.values.get(&key) == Some(value) {
|
|
||||||
self.values.remove(&key);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Keep only the drafts of `surface` whose node is in `live` (the ids of the republished tree);
|
|
||||||
/// other surfaces' drafts stay.
|
|
||||||
pub fn retain(&mut self, surface: &str, live: &HashSet<NodeId>) {
|
|
||||||
self.values.retain(|(held, node), _| held != surface || live.contains(node));
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn len(&self) -> usize {
|
|
||||||
self.values.len()
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn is_empty(&self) -> bool {
|
|
||||||
self.values.is_empty()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What a node's site currently shows: the draft over the bound value. The one place that rule is
|
|
||||||
/// written, read by render (through its `Session`) and by pointer input (a Toggle flips what is shown).
|
|
||||||
/// Only a draft of the site's own kind counts: a Number draft in a TextInput shows as its number.
|
|
||||||
pub fn current<'a>(tree: &'a BoundTree, drafts: Option<&'a Drafts>, node: &NodeId, field: Field) -> Option<Cow<'a, Bound>> {
|
|
||||||
let draft = drafts.and_then(|drafts| drafts.get(&tree.resolved().document().record_key(), node));
|
|
||||||
let shown = match (field, draft) {
|
|
||||||
(Field::Checked, Some(InputValue::Bool(held))) => Some(Bound::Bool(held.value)),
|
|
||||||
(Field::Value, Some(InputValue::Number(held))) => Some(Bound::Number(held.value)),
|
|
||||||
(Field::Selected, Some(InputValue::Choice(held))) => Some(Bound::Text(held.value.clone())),
|
|
||||||
(Field::Initial, Some(InputValue::Text(held))) => Some(Bound::Text(held.value.clone())),
|
|
||||||
(Field::Initial, Some(InputValue::Number(held))) => Some(Bound::Text(held.value.to_string())),
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
match shown {
|
|
||||||
Some(bound) => Some(Cow::Owned(bound)),
|
|
||||||
None => tree.value(node, field).map(Cow::Borrowed),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,83 +0,0 @@
|
||||||
//! The closed input model every host speaks to core. It is not `#[non_exhaustive]`: a new
|
|
||||||
//! variant is a contract revision every host compiles against.
|
|
||||||
//!
|
|
||||||
//! The viewport and the scale are not events: they are `FrameInput` fields, and a resize is the
|
|
||||||
//! next frame's viewport. Time is not an event either (`FrameInput::now`).
|
|
||||||
|
|
||||||
/// One thing the user did, in the order the host saw it.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub enum InputEvent {
|
|
||||||
/// A key press or auto-repeat (`repeat: true`). A release never enters: a terminal
|
|
||||||
/// reports Release on Windows and the TUI drops it, and the web host drops keyup. `Char` is the
|
|
||||||
/// character the keyboard layout produced (Shift+a is `Char('A')` with `shift` set;
|
|
||||||
/// Shift+Tab is `Tab` with `shift`). A typing key emits `Key` then `Text`, in that order (DOM
|
|
||||||
/// keydown precedes beforeinput; a window system's key event carries text beside the key; egui emits
|
|
||||||
/// Event::Key then Event::Text); a Ctrl or Alt chord emits `Key` only. Commands bind to `Key`.
|
|
||||||
Key { key: Key, modifiers: Modifiers, repeat: bool },
|
|
||||||
/// Committed text to insert; a paste is `Text`. Text inserts only from `Text`, so nothing
|
|
||||||
/// inserts twice.
|
|
||||||
Text(String),
|
|
||||||
/// The IME preedit, replacing any earlier one; empty `text` ends it without commit, and the
|
|
||||||
/// commit arrives as `Text` (DOM compositionupdate/compositionend; a window system's IME preedit and commit).
|
|
||||||
/// `cursor` is UTF-8 byte offsets into `text`, the window-system convention; the web host converts the
|
|
||||||
/// DOM's UTF-16 offsets.
|
|
||||||
Compose { text: String, cursor: Option<(u32, u32)> },
|
|
||||||
/// `at` is in the space `Placed` is in: logical px, or cells where a terminal cell
|
|
||||||
/// `(col, row)` is its centre `(col + 0.5, row + 0.5)`, the point the TUI's paint covers a
|
|
||||||
/// cell by, so a hit and a drawn cell agree.
|
|
||||||
PointerDown { at: (f32, f32), button: PointerButton, modifiers: Modifiers },
|
|
||||||
/// Sent with or without a button held.
|
|
||||||
PointerMove { at: (f32, f32), modifiers: Modifiers },
|
|
||||||
PointerUp { at: (f32, f32), button: PointerButton, modifiers: Modifiers },
|
|
||||||
/// The platform took the pointer (DOM pointercancel; the web host uses setPointerCapture so
|
|
||||||
/// an up outside the canvas still arrives): a pending press is dropped and no up follows.
|
|
||||||
PointerCancel,
|
|
||||||
/// `delta` positive y moves content toward its end (the scroll offset grows), positive x
|
|
||||||
/// right: the DOM WheelEvent sign. A terminal's ScrollDown is `(0, 1)` `Lines`; a
|
|
||||||
/// window system whose line delta has the opposite sign is negated by its host. `Units` are logical px or
|
|
||||||
/// cells; `Lines` are converted by core.
|
|
||||||
Wheel { at: (f32, f32), delta: (f32, f32), unit: WheelUnit, modifiers: Modifiers },
|
|
||||||
/// The host window or terminal gained (`true`) or lost focus.
|
|
||||||
Focus(bool),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
|
||||||
pub enum Key {
|
|
||||||
Char(char),
|
|
||||||
Enter,
|
|
||||||
Tab,
|
|
||||||
Backspace,
|
|
||||||
Delete,
|
|
||||||
Escape,
|
|
||||||
Left,
|
|
||||||
Right,
|
|
||||||
Up,
|
|
||||||
Down,
|
|
||||||
Home,
|
|
||||||
End,
|
|
||||||
PageUp,
|
|
||||||
PageDown,
|
|
||||||
Insert,
|
|
||||||
F(u8),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
|
||||||
pub struct Modifiers {
|
|
||||||
pub shift: bool,
|
|
||||||
pub ctrl: bool,
|
|
||||||
pub alt: bool,
|
|
||||||
pub meta: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
|
||||||
pub enum PointerButton {
|
|
||||||
Primary,
|
|
||||||
Secondary,
|
|
||||||
Middle,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
|
||||||
pub enum WheelUnit {
|
|
||||||
Units,
|
|
||||||
Lines,
|
|
||||||
}
|
|
||||||
|
|
@ -1,102 +0,0 @@
|
||||||
//! Hit-testing: which node a point reaches, read from the geometry render placed and nothing else.
|
|
||||||
//! The point is in the space `Placed` is in (logical px, or cells), so this file applies no scroll or
|
|
||||||
//! clip of its own: render already did, and `Placed::visible` is what the user could see. `k` (device px
|
|
||||||
//! per logical px, from `render::device_scale`) only puts point and edges on the device grid layout laid.
|
|
||||||
//! Paint order is the only layer order: the last placed node under the point wins, overlays are last,
|
|
||||||
//! and a modal overlay shuts out everything painted before it.
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
use thing_contract::{Node, NodeId};
|
|
||||||
|
|
||||||
use crate::layout::{LaidTree, Rect};
|
|
||||||
use crate::render::Rendered;
|
|
||||||
|
|
||||||
/// What a press can activate: a control, or a modal's scrim (its dismissal).
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub(super) enum Control {
|
|
||||||
Button,
|
|
||||||
Toggle,
|
|
||||||
Slider,
|
|
||||||
Select,
|
|
||||||
TextInput,
|
|
||||||
Scrim,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub(super) struct Target {
|
|
||||||
pub(super) node: NodeId,
|
|
||||||
pub(super) control: Control,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where a point lands before any node is asked what it takes: the topmost node under it, or the
|
|
||||||
/// modal overlay (by laid index) when the point reaches nothing inside it.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub(super) enum Reach {
|
|
||||||
Node(usize),
|
|
||||||
Scrim(usize),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A coordinate on the device grid, held to 1/1024 px. Layout lays whole device pixels, render divides
|
|
||||||
/// them by the scale, and a pointer is that logical coordinate again: `k` times it is the device pixel
|
|
||||||
/// only up to the rounding error of dividing and multiplying back, which at a fractional scale is enough to
|
|
||||||
/// put the first pixel past an edge inside it. The grid is coarser than that error and finer than any
|
|
||||||
/// pixel, so an edge and a pointer that mean the same device position compare equal.
|
|
||||||
fn on_device(logical: f32, k: f32) -> f32 {
|
|
||||||
const GRID: f32 = 1024.0;
|
|
||||||
(logical * k * GRID).round() / GRID
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Half-open on the device grid: a node's right and bottom edges belong to its neighbour.
|
|
||||||
fn covers(rect: Rect, (x, y): (f32, f32), k: f32) -> bool {
|
|
||||||
let (x, y) = (on_device(x, k), on_device(y, k));
|
|
||||||
x >= on_device(rect.x, k) && x < on_device(rect.x + rect.w, k) && y >= on_device(rect.y, k) && y < on_device(rect.y + rect.h, k)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn reach(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeId, &Node>, point: (f32, f32), k: f32) -> Option<Reach> {
|
|
||||||
// The last modal overlay root in paint order: nothing painted before it is reachable, and what
|
|
||||||
// is painted after it (its own subtree, then any later overlay) is.
|
|
||||||
let modal = laid
|
|
||||||
.nodes
|
|
||||||
.iter()
|
|
||||||
.rposition(|node| node.parent.is_none() && matches!(index.get(&node.id), Some(Node::Overlay(overlay)) if overlay.modal));
|
|
||||||
let floor = modal.map_or(0, |m| m + 1);
|
|
||||||
// A non-modal overlay's root is only where its content is anchored: it is the viewport or the
|
|
||||||
// anchor's rect, not something drawn, so a press that misses the content goes on through it.
|
|
||||||
let transparent = |i: usize| laid.nodes[i].parent.is_none() && matches!(index.get(&laid.nodes[i].id), Some(Node::Overlay(_)));
|
|
||||||
let top = rendered.placed.iter().enumerate().skip(floor).rev().find(|(i, placed)| !transparent(*i) && placed.visible.is_some_and(|seen| covers(seen, point, k)));
|
|
||||||
match (top, modal) {
|
|
||||||
(Some((i, _)), _) => Some(Reach::Node(i)),
|
|
||||||
(None, Some(m)) => Some(Reach::Scrim(m)),
|
|
||||||
(None, None) => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn control_of(node: &Node) -> Option<Control> {
|
|
||||||
match node {
|
|
||||||
Node::Button(_) => Some(Control::Button),
|
|
||||||
Node::Toggle(_) => Some(Control::Toggle),
|
|
||||||
Node::Slider(_) => Some(Control::Slider),
|
|
||||||
Node::Select(_) => Some(Control::Select),
|
|
||||||
Node::TextInput(_) => Some(Control::TextInput),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The node `point` activates: the nearest activatable node at or above the topmost one under it
|
|
||||||
/// (a Button's label hits the Button), or a modal's scrim. A point on a Box, on text outside a
|
|
||||||
/// control or on a non-modal overlay's root targets nothing.
|
|
||||||
pub(super) fn target(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeId, &Node>, point: (f32, f32), k: f32) -> Option<Target> {
|
|
||||||
let mut at = match reach(rendered, laid, index, point, k)? {
|
|
||||||
Reach::Scrim(m) => return Some(Target { node: laid.nodes[m].id.clone(), control: Control::Scrim }),
|
|
||||||
Reach::Node(i) => Some(i),
|
|
||||||
};
|
|
||||||
while let Some(i) = at {
|
|
||||||
let laid_node = laid.nodes.get(i)?;
|
|
||||||
if let Some(control) = index.get(&laid_node.id).copied().and_then(control_of) {
|
|
||||||
return Some(Target { node: laid_node.id.clone(), control });
|
|
||||||
}
|
|
||||||
at = laid_node.parent.map(|parent| parent as usize);
|
|
||||||
}
|
|
||||||
None
|
|
||||||
}
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
//! What a host tells core about its user: the closed `InputEvent` vocabulary, the `Drafts` table
|
|
||||||
//! that owns what the user has typed or chosen and not yet sent, hit-testing against the frame the
|
|
||||||
//! user saw, and the pointer routes that turn a press, a drag or a wheel into an activation, a draft
|
|
||||||
//! or a scroll offset.
|
|
||||||
|
|
||||||
pub mod drafts;
|
|
||||||
pub mod event;
|
|
||||||
mod hit;
|
|
||||||
mod pointer;
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests;
|
|
||||||
|
|
||||||
pub use drafts::{Drafts, current};
|
|
||||||
pub use event::{InputEvent, Key, Modifiers, PointerButton, WheelUnit};
|
|
||||||
pub(crate) use pointer::{Input, Owners, Seen};
|
|
||||||
|
|
@ -1,210 +0,0 @@
|
||||||
//! Pointer input: press state and the routes from a pointer event to the one activation primitive,
|
|
||||||
//! to `Drafts` (a Slider drag) and to `ScrollOffsets` (the wheel). Input decides which node an
|
|
||||||
//! event reaches and nothing about what a command does: every commit ends in `Commands::activate`.
|
|
||||||
|
|
||||||
use thing_contract::{BoolValue, InputValue, Node, NodeId, NumberValue, SliderNode};
|
|
||||||
|
|
||||||
use super::drafts::{Drafts, current};
|
|
||||||
use super::event::{InputEvent, PointerButton, WheelUnit};
|
|
||||||
use super::hit::{Control, Reach, Target, reach, target};
|
|
||||||
use crate::bind::{Bound, BoundTree, Field};
|
|
||||||
use crate::command::{Activation, ActivationKind, Commands};
|
|
||||||
use crate::diagnostic::Diagnostic;
|
|
||||||
use crate::layout::{LaidTree, Metrics, Rect};
|
|
||||||
use crate::port::{IdSource, Ledger, StatePort};
|
|
||||||
use crate::render::{Rendered, ScrollOffsets, clamp, device_scale};
|
|
||||||
use crate::time::Timestamp;
|
|
||||||
|
|
||||||
/// The last good frame and how it was drawn: what every event is judged against.
|
|
||||||
pub(crate) struct Seen<'a> {
|
|
||||||
pub(crate) rendered: &'a Rendered,
|
|
||||||
pub(crate) laid: &'a LaidTree,
|
|
||||||
pub(crate) tree: &'a BoundTree,
|
|
||||||
pub(crate) metrics: Metrics,
|
|
||||||
/// Device px per logical px (Pixels), which turns a wheel's logical units into the device px
|
|
||||||
/// scroll offsets are held in.
|
|
||||||
pub(crate) scale: f32,
|
|
||||||
/// The theme's body text size in logical px: what one wheel line is in Pixels. A guess, unmeasured.
|
|
||||||
pub(crate) line: f32,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Seen<'_> {
|
|
||||||
/// Device px per logical px, which is what a pointer is multiplied by to land on laid pixels.
|
|
||||||
fn k(&self) -> f32 {
|
|
||||||
device_scale(self.metrics, self.scale)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The owners an event writes through: activation, drafts and scroll positions.
|
|
||||||
pub(crate) struct Owners<'a> {
|
|
||||||
pub(crate) commands: &'a mut Commands,
|
|
||||||
pub(crate) drafts: &'a mut Drafts,
|
|
||||||
pub(crate) scroll: &'a mut ScrollOffsets,
|
|
||||||
pub(crate) ids: &'a mut dyn IdSource,
|
|
||||||
pub(crate) port: &'a mut dyn StatePort,
|
|
||||||
pub(crate) ledger: &'a mut Ledger,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The one press in progress. A Slider's press also holds the draft it replaced, so a cancel can put it back.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
enum Press {
|
|
||||||
Target(Target),
|
|
||||||
Drag { node: NodeId, prior: Option<InputValue> },
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The owner of press state. No node holds a pressed or hover flag.
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq)]
|
|
||||||
struct Pointer {
|
|
||||||
press: Option<Press>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The routes every pointer and wheel event takes; it owns the `Pointer`.
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq)]
|
|
||||||
pub(crate) struct Input {
|
|
||||||
pointer: Pointer,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The value a press at `x` on a Slider's track `rect` chooses: along `[min, max]`, snapped to `step`
|
|
||||||
/// from `min`, held in range. None when the slider has no usable range or track.
|
|
||||||
fn slider_value(slider: &SliderNode, rect: Rect, x: f32) -> Option<f64> {
|
|
||||||
if !(slider.min.is_finite() && slider.max.is_finite() && slider.min < slider.max && rect.w > 0.0 && x.is_finite()) {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let along = f64::from((x - rect.x) / rect.w);
|
|
||||||
let raw = slider.min + along * (slider.max - slider.min);
|
|
||||||
let snapped = if slider.step.is_finite() && slider.step > 0.0 { slider.min + ((raw - slider.min) / slider.step).round() * slider.step } else { raw };
|
|
||||||
Some(snapped.clamp(slider.min, slider.max))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn placed_rect(rendered: &Rendered, node: &NodeId) -> Option<Rect> {
|
|
||||||
rendered.placed.iter().find(|placed| &placed.id == node).map(|placed| placed.rect)
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Input {
|
|
||||||
pub(crate) fn new() -> Self {
|
|
||||||
Self::default()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Drop the press in progress, as the platform taking the pointer does, and as leaving the
|
|
||||||
/// surface does: a Slider draft the press wrote goes back to what it was.
|
|
||||||
pub(crate) fn cancel(&mut self, surface: &str, drafts: &mut Drafts) {
|
|
||||||
if let Some(Press::Drag { node, prior }) = self.pointer.press.take() {
|
|
||||||
drafts.restore(surface, &node, prior);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Route one event. Keys, text, composition and the window gaining or losing the user are not pointer input and change nothing,
|
|
||||||
/// and only the primary button presses. The diagnostics are the activations' refusals.
|
|
||||||
pub(crate) fn event(&mut self, event: &InputEvent, seen: &Seen<'_>, owners: &mut Owners<'_>, now: Timestamp) -> Vec<Diagnostic> {
|
|
||||||
let surface = seen.tree.resolved().document().record_key();
|
|
||||||
match event {
|
|
||||||
InputEvent::PointerDown { at, button: PointerButton::Primary, .. } => return self.down(*at, seen, owners, &surface),
|
|
||||||
InputEvent::PointerMove { at, .. } => return self.drag(*at, seen, owners, &surface),
|
|
||||||
InputEvent::PointerUp { at, button: PointerButton::Primary, .. } => return self.up(*at, seen, owners, now, &surface),
|
|
||||||
InputEvent::PointerCancel => self.cancel(&surface, owners.drafts),
|
|
||||||
InputEvent::Wheel { at, delta, unit, .. } => wheel(*at, *delta, *unit, seen, owners.scroll),
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
Vec::new()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn down(&mut self, at: (f32, f32), seen: &Seen<'_>, owners: &mut Owners<'_>, surface: &str) -> Vec<Diagnostic> {
|
|
||||||
// A press never starts over another: the one in progress ends first.
|
|
||||||
self.cancel(surface, owners.drafts);
|
|
||||||
let index = seen.tree.index();
|
|
||||||
let mut said = Vec::new();
|
|
||||||
self.pointer.press = target(seen.rendered, seen.laid, &index, at, seen.k()).and_then(|hit| match (hit.control, index.get(&hit.node)) {
|
|
||||||
(Control::Slider, Some(Node::Slider(slider))) => {
|
|
||||||
let value = placed_rect(seen.rendered, &hit.node).and_then(|rect| slider_value(slider, rect, at.0))?;
|
|
||||||
// A slider that takes no change takes no press: nothing is drafted, so nothing is left unsent.
|
|
||||||
if let Some(held) = owners.commands.refuses_change(seen.tree, &hit.node) {
|
|
||||||
said.push(held);
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let prior = owners.drafts.get(surface, &hit.node).cloned();
|
|
||||||
owners.drafts.set(surface, &hit.node, InputValue::Number(NumberValue { value }));
|
|
||||||
Some(Press::Drag { node: hit.node, prior })
|
|
||||||
}
|
|
||||||
_ => Some(Press::Target(hit)),
|
|
||||||
});
|
|
||||||
said
|
|
||||||
}
|
|
||||||
|
|
||||||
fn drag(&mut self, at: (f32, f32), seen: &Seen<'_>, owners: &mut Owners<'_>, surface: &str) -> Vec<Diagnostic> {
|
|
||||||
let Some(Press::Drag { node, .. }) = &self.pointer.press else { return Vec::new() };
|
|
||||||
let index = seen.tree.index();
|
|
||||||
let Some(Node::Slider(slider)) = index.get(node) else { return Vec::new() };
|
|
||||||
if let Some(held) = owners.commands.refuses_change(seen.tree, node) {
|
|
||||||
return vec![held];
|
|
||||||
}
|
|
||||||
if let Some(value) = placed_rect(seen.rendered, node).and_then(|rect| slider_value(slider, rect, at.0)) {
|
|
||||||
owners.drafts.set(surface, node, InputValue::Number(NumberValue { value }));
|
|
||||||
}
|
|
||||||
Vec::new()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn up(&mut self, at: (f32, f32), seen: &Seen<'_>, owners: &mut Owners<'_>, now: Timestamp, surface: &str) -> Vec<Diagnostic> {
|
|
||||||
let activation = match self.pointer.press.take() {
|
|
||||||
None => return Vec::new(),
|
|
||||||
// A drag commits the draft it wrote, wherever the pointer is let go.
|
|
||||||
Some(Press::Drag { node, .. }) => match owners.drafts.get(surface, &node) {
|
|
||||||
Some(value) => Activation { node, kind: ActivationKind::Change(value.clone()) },
|
|
||||||
None => return Vec::new(),
|
|
||||||
},
|
|
||||||
Some(Press::Target(pressed)) => {
|
|
||||||
if target(seen.rendered, seen.laid, &seen.tree.index(), at, seen.k()).as_ref() != Some(&pressed) {
|
|
||||||
return Vec::new();
|
|
||||||
}
|
|
||||||
match pressed.control {
|
|
||||||
Control::Button | Control::Scrim => Activation { node: pressed.node, kind: ActivationKind::Press },
|
|
||||||
Control::Toggle => {
|
|
||||||
let shown = current(seen.tree, Some(owners.drafts), &pressed.node, Field::Checked);
|
|
||||||
let checked = matches!(shown.as_deref(), Some(Bound::Bool(true)));
|
|
||||||
Activation { node: pressed.node, kind: ActivationKind::Change(InputValue::Bool(BoolValue { value: !checked })) }
|
|
||||||
}
|
|
||||||
// A Select's chooser and a TextInput's editing are not here: a press on them does nothing, and
|
|
||||||
// does not fall through to a control around them. A Slider's press is a `Drag`, never a target.
|
|
||||||
Control::Slider | Control::Select | Control::TextInput => return Vec::new(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
owners.commands.activate(activation, seen.tree, owners.drafts, now, owners.ids, owners.port, owners.ledger)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The wheel moves the nearest scroll node at or above what it is over, on the wheel's axis, that
|
|
||||||
/// has room to move that way; at the end of its travel the next scroll ancestor takes it. Under a
|
|
||||||
/// modal only the modal's own subtree is reachable. Offsets are held in device px (Pixels) or cells.
|
|
||||||
fn wheel(at: (f32, f32), delta: (f32, f32), unit: WheelUnit, seen: &Seen<'_>, scroll: &mut ScrollOffsets) {
|
|
||||||
let index = seen.tree.index();
|
|
||||||
let Some(Reach::Node(start) | Reach::Scrim(start)) = reach(seen.rendered, seen.laid, &index, at, seen.k()) else { return };
|
|
||||||
let to_device = seen.k();
|
|
||||||
let line = match seen.metrics {
|
|
||||||
Metrics::Cells => 1.0,
|
|
||||||
Metrics::Pixels => seen.line,
|
|
||||||
};
|
|
||||||
let per = match unit {
|
|
||||||
WheelUnit::Units => to_device,
|
|
||||||
WheelUnit::Lines => line * to_device,
|
|
||||||
};
|
|
||||||
for axis in [0usize, 1] {
|
|
||||||
let amount = [delta.0, delta.1][axis] * per;
|
|
||||||
if !amount.is_finite() || amount == 0.0 {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let mut over = Some(start);
|
|
||||||
while let Some(i) = over {
|
|
||||||
let node = &seen.laid.nodes[i];
|
|
||||||
if let Some(max) = node.max_scroll {
|
|
||||||
let held = scroll.of(node);
|
|
||||||
let want = if axis == 0 { (held.0 + amount, held.1) } else { (held.0, held.1 + amount) };
|
|
||||||
let next = clamp(want, max);
|
|
||||||
if next != held {
|
|
||||||
scroll.set(node.id.clone(), next);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
over = node.parent.map(|parent| parent as usize);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,959 +0,0 @@
|
||||||
//! Pointer input: a press, a drag and a wheel reach the node the user saw drawn, in Pixels (at several
|
|
||||||
//! scales) and in Cells, and end in the one activation primitive, in drafts or in scroll offsets.
|
|
||||||
//! Hit-testing reads the geometry render placed, so every test derives its points from `Placed`
|
|
||||||
//! and never from authored numbers. These tests live in the crate because `Input`, `Seen` and `Owners`
|
|
||||||
//! are not public; for the same reason they cannot use `thing-testkit`'s state port (its types name the
|
|
||||||
//! library build of this crate, not this test build), so `Port`, `Counter` and `Boxes` below are the three
|
|
||||||
//! small doubles they need. The contract documents they press are `tests/support`, shared with the host tests.
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
use thing_contract::*;
|
|
||||||
use thing_testkit::build::*;
|
|
||||||
|
|
||||||
use super::hit::{Reach, Target, reach, target};
|
|
||||||
use super::pointer::{Owners, Seen};
|
|
||||||
use super::{Drafts, Input, InputEvent, Modifiers, PointerButton, WheelUnit};
|
|
||||||
use crate::bind::{Binder, BoundTree, Instance};
|
|
||||||
use crate::command::Commands;
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
use crate::layout::{Constraint, LaidTree, LayoutFrame, Leaf, Measure, Metrics, Rect, TextLayout, TextRequest, layout};
|
|
||||||
use crate::port::{Address, Change, Entry, IdSource, Interest, Ledger, Lookup, Prefix, Record, StatePort, StateValue, SubscriptionId};
|
|
||||||
use crate::render::{RenderInput, Rendered, ScrollOffsets, Session, render};
|
|
||||||
use crate::resolve::{Limits, resolve};
|
|
||||||
use crate::theme::Theme;
|
|
||||||
use crate::time::Timestamp;
|
|
||||||
|
|
||||||
#[path = "../../tests/support/mod.rs"]
|
|
||||||
mod support;
|
|
||||||
use support::*;
|
|
||||||
|
|
||||||
/// Records by address, the interests asked of the port and the changes queued for a drain.
|
|
||||||
#[derive(Clone, Default)]
|
|
||||||
struct Port {
|
|
||||||
records: HashMap<Address, Entry>,
|
|
||||||
interests: Vec<(SubscriptionId, Interest)>,
|
|
||||||
queue: Vec<Change>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Port {
|
|
||||||
fn new() -> Self {
|
|
||||||
Self::default()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn put(&mut self, provider: &ProviderId, document: &SurfaceDocument) {
|
|
||||||
let address = Address { provider: provider.clone(), schema: SchemaId::new(SurfaceDocument::SCHEMA_NAME), key: RecordKey::new(document.record_key()) };
|
|
||||||
self.records.insert(address.clone(), Entry { address, record: Record::Surface(document.clone()) });
|
|
||||||
}
|
|
||||||
|
|
||||||
fn put_item(&mut self, provider: &ProviderId, id: &str, title: &str) {
|
|
||||||
let address = Address { provider: provider.clone(), schema: SchemaId::new("gamecult.thing.test.item.v1"), key: RecordKey::new(id) };
|
|
||||||
let value = StateValue::Record(vec![("Id".into(), StateValue::Text(id.into())), ("Title".into(), StateValue::Text(title.into()))]);
|
|
||||||
let record = Record::State { schema: address.schema.clone(), value };
|
|
||||||
self.records.insert(address.clone(), Entry { address, record });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl StatePort for Port {
|
|
||||||
fn read(&self, address: &Address) -> Lookup {
|
|
||||||
self.records.get(address).map_or(Lookup::Absent, |entry| Lookup::Present(entry.clone()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn list(&self, prefix: &Prefix) -> Vec<Lookup> {
|
|
||||||
let mut held: Vec<_> = self.records.values().filter(|entry| prefix.matches(&entry.address)).collect();
|
|
||||||
held.sort_by(|a, b| a.address.key.as_str().cmp(b.address.key.as_str()));
|
|
||||||
held.into_iter().map(|entry| Lookup::Present(entry.clone())).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn subscribe(&mut self, interest: Interest) -> SubscriptionId {
|
|
||||||
let id = SubscriptionId(self.interests.len() as u64);
|
|
||||||
self.interests.push((id, interest));
|
|
||||||
id
|
|
||||||
}
|
|
||||||
|
|
||||||
fn unsubscribe(&mut self, id: SubscriptionId) {
|
|
||||||
self.interests.retain(|(held, _)| *held != id);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn drain(&mut self) -> Vec<Change> {
|
|
||||||
std::mem::take(&mut self.queue)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Ids that differ by a counter.
|
|
||||||
#[derive(Default)]
|
|
||||||
struct Counter(u128);
|
|
||||||
|
|
||||||
impl IdSource for Counter {
|
|
||||||
fn fill(&mut self, bytes: &mut [u8; 16]) {
|
|
||||||
self.0 += 1;
|
|
||||||
*bytes = self.0.to_be_bytes();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Fixed control sizes and no text: these documents hold boxes and controls only.
|
|
||||||
struct Boxes {
|
|
||||||
cells: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Measure for Boxes {
|
|
||||||
fn measure(&mut self, leaf: &Leaf, _: Constraint) -> (f32, f32) {
|
|
||||||
let control = |w: f32, h: f32| if self.cells { (w / 8.0, 1.0) } else { (w, h) };
|
|
||||||
match leaf {
|
|
||||||
Leaf::TextInput { multiline, .. } => control(200.0, if *multiline { 72.0 } else { 24.0 }),
|
|
||||||
Leaf::Toggle { .. } => control(40.0, 20.0),
|
|
||||||
Leaf::Slider { .. } => control(160.0, 20.0),
|
|
||||||
Leaf::Select { .. } => control(160.0, 24.0),
|
|
||||||
Leaf::Text { .. } | Leaf::Image { .. } => (0.0, 0.0),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn text(&mut self, _: &TextRequest, _: f32) -> TextLayout {
|
|
||||||
TextLayout { lines: vec![] }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Pixels at two scales, and Cells: the modes the pointer must agree with the laid geometry in.
|
|
||||||
const MODES: [(Metrics, f32); 3] = [(Metrics::Pixels, 1.0), (Metrics::Pixels, 1.5), (Metrics::Cells, 1.0)];
|
|
||||||
|
|
||||||
fn viewport(metrics: Metrics) -> (f32, f32) {
|
|
||||||
match metrics {
|
|
||||||
Metrics::Pixels => (400.0, 320.0),
|
|
||||||
Metrics::Cells => (50.0, 20.0),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn measure(metrics: Metrics) -> Boxes {
|
|
||||||
Boxes { cells: metrics == Metrics::Cells }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn row_id(item: &str, node: &str) -> NodeId {
|
|
||||||
NodeId::new(format!("{}{node}", Instance::scope_prefix("rows", item, false)))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn feed() -> Port {
|
|
||||||
let mut state = Port::new();
|
|
||||||
for n in 0..20 {
|
|
||||||
let id = format!("item-{n:04}");
|
|
||||||
state.put_item(&ProviderId::new(FEED), &id, &id);
|
|
||||||
}
|
|
||||||
state
|
|
||||||
}
|
|
||||||
|
|
||||||
// ----- the rig: the stages composed by hand, with the owners input writes through -----
|
|
||||||
|
|
||||||
struct Rig {
|
|
||||||
tree: BoundTree,
|
|
||||||
laid: LaidTree,
|
|
||||||
rendered: Rendered,
|
|
||||||
metrics: Metrics,
|
|
||||||
scale: f32,
|
|
||||||
surface: String,
|
|
||||||
state: Port,
|
|
||||||
ledger: Ledger,
|
|
||||||
input: Input,
|
|
||||||
commands: Commands,
|
|
||||||
drafts: Drafts,
|
|
||||||
scroll: ScrollOffsets,
|
|
||||||
ids: Counter,
|
|
||||||
now: Timestamp,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Rig {
|
|
||||||
fn new(mut state: Port, document: &SurfaceDocument, (metrics, scale): (Metrics, f32)) -> Self {
|
|
||||||
state.put(&document.provider_id, document);
|
|
||||||
let limits = Limits::default();
|
|
||||||
let resolved = resolve(document, &state, &limits).tree.expect("resolves");
|
|
||||||
let mut ledger = Ledger::new();
|
|
||||||
let mut binder = Binder::new(limits);
|
|
||||||
binder.bind(resolved, &mut state, &mut ledger);
|
|
||||||
let tree = binder.tree(&document.record_key()).expect("bound").clone();
|
|
||||||
let mut rig = Self {
|
|
||||||
laid: LaidTree { nodes: vec![], diagnostics: vec![] },
|
|
||||||
rendered: Rendered { commands: vec![], placed: vec![], diagnostics: vec![] },
|
|
||||||
tree,
|
|
||||||
metrics,
|
|
||||||
scale,
|
|
||||||
surface: document.record_key(),
|
|
||||||
state,
|
|
||||||
ledger,
|
|
||||||
input: Input::new(),
|
|
||||||
commands: Commands::new("renderer.test", 15_000),
|
|
||||||
drafts: Drafts::new(),
|
|
||||||
scroll: ScrollOffsets::default(),
|
|
||||||
ids: Counter::default(),
|
|
||||||
now: Timestamp(0),
|
|
||||||
};
|
|
||||||
rig.draw();
|
|
||||||
rig
|
|
||||||
}
|
|
||||||
|
|
||||||
fn frame(&self) -> LayoutFrame {
|
|
||||||
LayoutFrame { viewport: viewport(self.metrics), scale: self.scale, metrics: self.metrics }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The frame the user sees: layout, then render over the scroll offsets, drafts and node states.
|
|
||||||
fn draw(&mut self) {
|
|
||||||
self.laid = layout(&self.tree, &self.frame(), &mut measure(self.metrics)).expect("lays out");
|
|
||||||
let states = self.commands.view(&self.surface);
|
|
||||||
let theme = Theme::std();
|
|
||||||
let input = RenderInput {
|
|
||||||
scale: self.scale,
|
|
||||||
metrics: self.metrics,
|
|
||||||
viewport: viewport(self.metrics),
|
|
||||||
scroll: &self.scroll,
|
|
||||||
theme: &theme,
|
|
||||||
session: Session::new(&self.drafts, &states),
|
|
||||||
};
|
|
||||||
self.rendered = render(&self.tree, &self.laid, &input, &mut measure(self.metrics));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn rect(&self, id: &str) -> Rect {
|
|
||||||
self.rendered.placed.iter().find(|placed| placed.id.as_str() == id).unwrap_or_else(|| panic!("no node {id}")).rect
|
|
||||||
}
|
|
||||||
|
|
||||||
fn send(&mut self, event: InputEvent) -> Vec<Diagnostic> {
|
|
||||||
let theme = Theme::std();
|
|
||||||
let seen = Seen { rendered: &self.rendered, laid: &self.laid, tree: &self.tree, metrics: self.metrics, scale: self.scale, line: theme.text["body"].size };
|
|
||||||
let mut owners = Owners {
|
|
||||||
commands: &mut self.commands,
|
|
||||||
drafts: &mut self.drafts,
|
|
||||||
scroll: &mut self.scroll,
|
|
||||||
ids: &mut self.ids,
|
|
||||||
port: &mut self.state,
|
|
||||||
ledger: &mut self.ledger,
|
|
||||||
};
|
|
||||||
self.input.event(&event, &seen, &mut owners, self.now)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn click(&mut self, at: (f32, f32)) -> Vec<Diagnostic> {
|
|
||||||
let mut said = self.send(down(at));
|
|
||||||
said.extend(self.send(up(at)));
|
|
||||||
said
|
|
||||||
}
|
|
||||||
|
|
||||||
fn minted(&mut self) -> Vec<CommandInvocation> {
|
|
||||||
self.commands.take_outbound()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn draft(&self, node: &str) -> Option<InputValue> {
|
|
||||||
self.drafts.get(&self.surface, &nid(node)).cloned()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn offset(&self, node: &str) -> Option<(f32, f32)> {
|
|
||||||
self.scroll.get(&nid(node))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn max_scroll(&self, node: &str) -> (f32, f32) {
|
|
||||||
self.laid.nodes.iter().find(|laid| laid.id.as_str() == node).and_then(|laid| laid.max_scroll).expect("scrolls")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn mods() -> Modifiers {
|
|
||||||
Modifiers::default()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn down(at: (f32, f32)) -> InputEvent {
|
|
||||||
InputEvent::PointerDown { at, button: PointerButton::Primary, modifiers: mods() }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn up(at: (f32, f32)) -> InputEvent {
|
|
||||||
InputEvent::PointerUp { at, button: PointerButton::Primary, modifiers: mods() }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn mv(at: (f32, f32)) -> InputEvent {
|
|
||||||
InputEvent::PointerMove { at, modifiers: mods() }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn wheel(at: (f32, f32), delta: (f32, f32), unit: WheelUnit) -> InputEvent {
|
|
||||||
InputEvent::Wheel { at, delta, unit, modifiers: mods() }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The top-left cell (or, in Pixels, the half-pixel) of a rect: a point that is inside it in every mode.
|
|
||||||
fn inside(rect: Rect) -> (f32, f32) {
|
|
||||||
(rect.x + 0.5, rect.y + 0.5)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn commands_of(invocations: &[CommandInvocation]) -> Vec<&str> {
|
|
||||||
invocations.iter().map(|invocation| invocation.command.as_str()).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn index_of(rig: &Rig) -> std::collections::HashMap<&NodeId, &Node> {
|
|
||||||
rig.tree.index()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Device px per logical px, as input holds it.
|
|
||||||
fn device_k(rig: &Rig) -> f32 {
|
|
||||||
match rig.metrics {
|
|
||||||
Metrics::Pixels => rig.scale,
|
|
||||||
Metrics::Cells => 1.0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The node, or the modal whose scrim it is, that a point reaches.
|
|
||||||
fn hit_node(rig: &Rig, at: (f32, f32)) -> Option<String> {
|
|
||||||
match reach(&rig.rendered, &rig.laid, &index_of(rig), at, device_k(rig))? {
|
|
||||||
Reach::Node(i) | Reach::Scrim(i) => Some(rig.laid.nodes[i].id.as_str().to_string()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn rig_target(rig: &Rig, at: (f32, f32)) -> Option<Target> {
|
|
||||||
target(&rig.rendered, &rig.laid, &index_of(rig), at, device_k(rig))
|
|
||||||
}
|
|
||||||
|
|
||||||
// ----- hit-testing agrees with the laid geometry -----
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_point_inside_the_absolute_target_hits_target_and_one_on_the_board_only_hits_board() {
|
|
||||||
for mode in MODES {
|
|
||||||
let rig = Rig::new(Port::new(), &target_surface(), mode);
|
|
||||||
let (target, board) = (rig.rect("target"), rig.rect("board"));
|
|
||||||
// The far corner of the target.
|
|
||||||
let corner = (target.x + target.w - 0.5, target.y + target.h - 0.5);
|
|
||||||
assert_eq!(hit_node(&rig, corner).as_deref(), Some("target"), "{mode:?}");
|
|
||||||
assert_eq!(hit_node(&rig, inside(board)).as_deref(), Some("board"), "{mode:?}");
|
|
||||||
assert!(target.x > board.x && target.y > board.y, "{mode:?}: the target stands inside the board, away from its corner");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_rect_is_half_open_so_a_shared_edge_belongs_to_the_second_node() {
|
|
||||||
for mode in MODES {
|
|
||||||
let rig = Rig::new(Port::new(), &surface(column("root", None, Overflow::Visible, vec![button("a", "x", 160.0, 48.0), button("b", "x", 160.0, 48.0)]), vec![decl("x", &[])]), mode);
|
|
||||||
let (a, b) = (rig.rect("a"), rig.rect("b"));
|
|
||||||
assert_eq!(a.y + a.h, b.y, "{mode:?}: the buttons touch");
|
|
||||||
let edge = (a.x + 0.5, b.y);
|
|
||||||
assert!(rig_target(&rig, edge).is_some_and(|hit| hit.node.as_str() == "b"), "{mode:?}");
|
|
||||||
let last = (a.x + 0.5, b.y - 0.25);
|
|
||||||
assert!(rig_target(&rig, last).is_some_and(|hit| hit.node.as_str() == "a"), "{mode:?}");
|
|
||||||
let under = (b.x + 0.5, b.y + b.h);
|
|
||||||
assert_eq!(rig_target(&rig, under), None, "{mode:?}: the bottom edge is outside");
|
|
||||||
let beyond = (a.x + a.w, a.y + 0.5);
|
|
||||||
assert_ne!(rig_target(&rig, beyond).map(|hit| hit.node), Some(nid("a")), "{mode:?}: the right edge is outside");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn every_visible_node_is_reached_inside_its_own_visible_rect() {
|
|
||||||
let documents = [
|
|
||||||
(modal_surface(), Port::new()),
|
|
||||||
(rows_surface(), feed()),
|
|
||||||
(controls_surface(), Port::new()),
|
|
||||||
(nested_surface(), Port::new()),
|
|
||||||
(clip_surface(), Port::new()),
|
|
||||||
(nonmodal_surface(Anchor::Viewport), Port::new()),
|
|
||||||
(target_surface(), Port::new()),
|
|
||||||
];
|
|
||||||
for mode in MODES {
|
|
||||||
for (document, state) in &documents {
|
|
||||||
let rig = Rig::new(state.clone(), document, mode);
|
|
||||||
for placed in &rig.rendered.placed {
|
|
||||||
let Some(seen) = placed.visible.filter(|r| r.w >= 1.0 && r.h >= 1.0) else { continue };
|
|
||||||
let at = inside(seen);
|
|
||||||
let hit = hit_node(&rig, at).expect("something is there");
|
|
||||||
let reached = rig.rendered.placed.iter().find(|p| p.id.as_str() == hit).unwrap();
|
|
||||||
let within = reached.visible.is_some_and(|r| at.0 >= r.x && at.0 < r.x + r.w && at.1 >= r.y && at.1 < r.y + r.h);
|
|
||||||
assert!(within, "{mode:?} {}: {hit} reached at {at:?} is not drawn there", document.label.as_str());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_node_outside_its_clip_is_not_hit_where_its_rect_reaches_past_the_clip() {
|
|
||||||
for mode in MODES {
|
|
||||||
let rig = Rig::new(Port::new(), &clip_surface(), mode);
|
|
||||||
let (frame, tall) = (rig.rect("frame"), rig.rect("tall"));
|
|
||||||
assert!(tall.y + tall.h > frame.y + frame.h, "{mode:?}: the button runs past the clip");
|
|
||||||
let below = (tall.x + 0.5, frame.y + frame.h + 0.5);
|
|
||||||
assert!(below.1 < tall.y + tall.h);
|
|
||||||
assert_eq!(rig_target(&rig, below), None, "{mode:?}");
|
|
||||||
assert_ne!(hit_node(&rig, below).as_deref(), Some("tall"), "{mode:?}");
|
|
||||||
// Inside the clip it is hit.
|
|
||||||
let inside_clip = rig_target(&rig, inside(frame));
|
|
||||||
assert_eq!(inside_clip.map(|hit| hit.node.as_str().to_string()).as_deref(), Some("tall"), "{mode:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ----- the edge of a node, at a scale that does not divide -----
|
|
||||||
|
|
||||||
/// Rows of odd widths and heights, so edges fall between whole logical px at a fractional scale.
|
|
||||||
fn seam_surface() -> SurfaceDocument {
|
|
||||||
let row = |id: &str, h: f64, widths: &[f64]| {
|
|
||||||
let mut row = column(id, None, Overflow::Visible, widths.iter().enumerate().map(|(i, w)| fixed(&format!("{id}-{i}"), *w, h)).collect());
|
|
||||||
if let Node::Box(b) = &mut row {
|
|
||||||
b.style.direction = Direction::Row;
|
|
||||||
b.style.size = size2(Dimension::Percent(Scalar { value: 100.0 }), px(h));
|
|
||||||
b.style.justify_content = ContentAlign::Start;
|
|
||||||
}
|
|
||||||
row
|
|
||||||
};
|
|
||||||
surface(
|
|
||||||
column("root", None, Overflow::Visible, vec![
|
|
||||||
row("r0", 7.0, &[9.0, 14.0, 5.0, 31.0]),
|
|
||||||
row("r1", 13.0, &[11.0, 3.0, 17.0]),
|
|
||||||
row("r2", 5.0, &[6.0, 6.0, 6.0, 6.0, 7.0]),
|
|
||||||
row("r3", 19.0, &[23.0, 29.0, 13.0]),
|
|
||||||
]),
|
|
||||||
vec![],
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_first_device_pixel_past_a_nodes_right_or_bottom_edge_is_not_the_node_at_every_scale() {
|
|
||||||
let scales = [1.0, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0];
|
|
||||||
for mode in scales.map(|scale| (Metrics::Pixels, scale)) {
|
|
||||||
let rig = Rig::new(Port::new(), &seam_surface(), mode);
|
|
||||||
let k = device_k(&rig);
|
|
||||||
let mut leaves = 0;
|
|
||||||
for node in rig.laid.nodes.iter().filter(|node| node.id.as_str().contains('-')) {
|
|
||||||
leaves += 1;
|
|
||||||
let (id, r) = (node.id.as_str(), node.rect);
|
|
||||||
assert!(r.w >= 1.0 && r.h >= 1.0 && r.x.fract() == 0.0 && r.y.fract() == 0.0, "{mode:?} {id}: laid in whole device px, {r:?}");
|
|
||||||
// Device pixels, as a host at this scale reports a pointer: the pixel's corner and its centre.
|
|
||||||
let at = |dx: f32, dy: f32, off: f32| ((dx + off) / k, (dy + off) / k);
|
|
||||||
for off in [0.0, 0.5] {
|
|
||||||
let last = at(r.x + r.w - 1.0, r.y + r.h - 1.0, off);
|
|
||||||
assert_eq!(hit_node(&rig, last).as_deref(), Some(id), "{mode:?} {id} the last pixel of the node, +{off}");
|
|
||||||
let right = at(r.x + r.w, r.y, off);
|
|
||||||
assert_ne!(hit_node(&rig, right).as_deref(), Some(id), "{mode:?} {id} the pixel right of the node, +{off}");
|
|
||||||
let below = at(r.x, r.y + r.h, off);
|
|
||||||
assert_ne!(hit_node(&rig, below).as_deref(), Some(id), "{mode:?} {id} the pixel below the node, +{off}");
|
|
||||||
let first = at(r.x, r.y, off);
|
|
||||||
assert_eq!(hit_node(&rig, first).as_deref(), Some(id), "{mode:?} {id} the first pixel of the node, +{off}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
assert_eq!(leaves, 15, "{mode:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ----- a non-modal overlay -----
|
|
||||||
|
|
||||||
fn nonmodal_surface(anchor: Anchor) -> SurfaceDocument {
|
|
||||||
let pop = Node::Overlay(OverlayNode { common: common("pop"), anchor, modal: false, dismiss: command("dismiss"), children: vec![button("pop-button", "inside", 80.0, 48.0)] });
|
|
||||||
surface(
|
|
||||||
column("root", None, Overflow::Visible, vec![button("behind", "behind", 320.0, 48.0), button("other", "other", 320.0, 48.0), pop]),
|
|
||||||
vec![decl("behind", &[]), decl("other", &[]), decl("inside", &[]), decl("dismiss", &[])],
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_press_passes_through_a_non_modal_overlays_root_to_what_lies_beneath_and_its_own_content_still_takes_it() {
|
|
||||||
let node = Anchor::Node(AnchorNode { node: nid("behind") });
|
|
||||||
for mode in MODES {
|
|
||||||
for anchor in [Anchor::Viewport, node.clone()] {
|
|
||||||
let mut rig = Rig::new(Port::new(), &nonmodal_surface(anchor.clone()), mode);
|
|
||||||
let (behind, other, inner) = (rig.rect("behind"), rig.rect("other"), rig.rect("pop-button"));
|
|
||||||
let (a, b) = ((behind.x + behind.w - 0.5, behind.y + 0.5), (other.x + other.w - 0.5, other.y + 0.5));
|
|
||||||
for at in [a, b] {
|
|
||||||
assert!(!(at.0 >= inner.x && at.0 < inner.x + inner.w && at.1 >= inner.y && at.1 < inner.y + inner.h), "{mode:?} {anchor:?}: {at:?} is clear of the overlay's content");
|
|
||||||
assert_eq!(hit_node(&rig, at).as_deref().map(|id| id != "pop"), Some(true), "{mode:?} {anchor:?}: the overlay's root is not what is hit at {at:?}");
|
|
||||||
}
|
|
||||||
rig.click(a);
|
|
||||||
assert_eq!(commands_of(&rig.minted()), ["behind"], "{mode:?} {anchor:?}: the press reaches the anchor or the node under the viewport overlay");
|
|
||||||
rig.click(b);
|
|
||||||
assert_eq!(commands_of(&rig.minted()), ["other"], "{mode:?} {anchor:?}");
|
|
||||||
// The overlay's own content is drawn over them and takes its press.
|
|
||||||
rig.click(inside(inner));
|
|
||||||
assert_eq!(commands_of(&rig.minted()), ["inside"], "{mode:?} {anchor:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_wheel_over_a_non_modal_overlays_root_reaches_the_pane_beneath() {
|
|
||||||
let pane = column("pane", Some((160.0, 80.0)), Overflow::Scroll, vec![fixed("fill", 160.0, 400.0)]);
|
|
||||||
let document = surface(column("root", None, Overflow::Visible, vec![pane, overlay("pop", false, vec![fixed("pop-body", 8.0, 16.0)])]), vec![decl("dismiss", &[])]);
|
|
||||||
for mode in MODES {
|
|
||||||
let mut rig = Rig::new(Port::new(), &document, mode);
|
|
||||||
let pane = rig.rect("pane");
|
|
||||||
rig.send(wheel((pane.x + pane.w - 0.5, pane.y + pane.h - 0.5), (0.0, 16.0), WheelUnit::Units));
|
|
||||||
assert!(rig.offset("pane").is_some_and(|o| o.1 > 0.0), "{mode:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ----- the modal -----
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_modal_confirms_inside_the_dialog_and_dismisses_outside_it_and_never_reaches_beneath() {
|
|
||||||
for mode in MODES {
|
|
||||||
let mut rig = Rig::new(Port::new(), &modal_surface(), mode);
|
|
||||||
// Inside the dialog: the confirm button.
|
|
||||||
rig.click(inside(rig.rect("confirm")));
|
|
||||||
assert_eq!(commands_of(&rig.minted()), ["confirm"], "{mode:?}");
|
|
||||||
// Over a main-tree button under the scrim: the scrim's dismissal, once, and not the button's command.
|
|
||||||
let behind = rig.rect("behind");
|
|
||||||
rig.click((behind.x + behind.w - 0.5, behind.y + 0.5));
|
|
||||||
assert_eq!(commands_of(&rig.minted()), ["dismiss"], "{mode:?}");
|
|
||||||
// The dialog's own body is not the scrim: nothing.
|
|
||||||
let dialog = rig.rect("dialog");
|
|
||||||
rig.click((dialog.x + dialog.w - 0.5, dialog.y + dialog.h - 0.5));
|
|
||||||
assert_eq!(rig.minted(), vec![], "{mode:?}");
|
|
||||||
// The scrim is the whole viewport: a corner far from everything dismisses.
|
|
||||||
let (w, h) = viewport(mode.0);
|
|
||||||
let far = match mode.0 {
|
|
||||||
Metrics::Pixels => (w - 1.0, h - 1.0),
|
|
||||||
Metrics::Cells => (w - 0.5, h - 0.5),
|
|
||||||
};
|
|
||||||
assert_eq!(hit_node(&rig, far).as_deref(), Some("modal"), "{mode:?}");
|
|
||||||
// (The overlay that dismissed above still waits on its result, so it is silent: a fresh surface.)
|
|
||||||
let mut fresh = Rig::new(Port::new(), &modal_surface(), mode);
|
|
||||||
fresh.click(far);
|
|
||||||
assert_eq!(commands_of(&fresh.minted()), ["dismiss"], "{mode:?}");
|
|
||||||
// And the same press again, while the first waits, mints nothing more.
|
|
||||||
fresh.click(far);
|
|
||||||
assert_eq!(fresh.minted(), vec![], "{mode:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_press_on_the_scrim_released_on_a_button_activates_nothing() {
|
|
||||||
let mut rig = Rig::new(Port::new(), &modal_surface(), MODES[0]);
|
|
||||||
let behind = rig.rect("behind");
|
|
||||||
let (scrim, confirm) = ((behind.x + behind.w - 0.5, behind.y + 0.5), inside(rig.rect("confirm")));
|
|
||||||
rig.send(down(scrim));
|
|
||||||
rig.send(up(confirm));
|
|
||||||
assert_eq!(rig.minted(), vec![]);
|
|
||||||
}
|
|
||||||
|
|
||||||
// ----- scroll -----
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_click_hits_the_row_drawn_there_after_a_scroll_and_not_a_row_scrolled_out() {
|
|
||||||
for mode in MODES {
|
|
||||||
let mut rig = Rig::new(feed(), &rows_surface(), mode);
|
|
||||||
let (first, second) = (row_id("item-0000", "row"), row_id("item-0001", "row"));
|
|
||||||
let (r0, r1) = (rig.rect(first.as_str()), rig.rect(second.as_str()));
|
|
||||||
let step = r1.y - r0.y;
|
|
||||||
assert!(step > 0.0);
|
|
||||||
// At rest the click at row 0's corner is row 0, whose invocation names it in `items`.
|
|
||||||
rig.click(inside(r0));
|
|
||||||
let minted = rig.minted();
|
|
||||||
assert_eq!((minted[0].source.as_str(), minted[0].items.clone()), ("row", vec!["item-0000".to_string()]), "{mode:?}");
|
|
||||||
// Scrolled by one row (offsets are device px in Pixels): row 1 is drawn where row 0 was.
|
|
||||||
let k = if mode.0 == Metrics::Pixels { mode.1 } else { 1.0 };
|
|
||||||
rig.scroll.set(nid("pane"), (0.0, step * k));
|
|
||||||
rig.draw();
|
|
||||||
assert_eq!(rig.rect(second.as_str()).y, r0.y, "{mode:?}");
|
|
||||||
rig.click(inside(r0));
|
|
||||||
assert_eq!(rig.minted()[0].items, vec!["item-0001".to_string()], "{mode:?}");
|
|
||||||
// Row 0 is above the pane's clip now: its rect is not hit anywhere, though a point there is drawn.
|
|
||||||
let gone = rig.rendered.placed.iter().find(|p| p.id == first).unwrap();
|
|
||||||
let pane = rig.rect("pane");
|
|
||||||
let over = (pane.x + 0.5, gone.rect.y + 0.5);
|
|
||||||
assert!(over.1 < pane.y, "{mode:?}: the scrolled-out row is above the pane");
|
|
||||||
assert_ne!(hit_node(&rig, over).as_deref(), Some(first.as_str()), "{mode:?}");
|
|
||||||
assert_eq!(rig_target(&rig, over), None, "{mode:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_wheel_moves_the_pane_and_clamps_at_the_end_then_goes_to_the_next_pane() {
|
|
||||||
for mode in MODES {
|
|
||||||
let mut rig = Rig::new(Port::new(), &nested_surface(), mode);
|
|
||||||
let k = if mode.0 == Metrics::Pixels { mode.1 } else { 1.0 };
|
|
||||||
let (inner, outer) = (rig.rect("inner"), rig.rect("outer"));
|
|
||||||
let over = inside(inner);
|
|
||||||
let (inner_max, _) = (rig.max_scroll("inner"), 0);
|
|
||||||
assert!(inner_max.1 > 0.0 && rig.max_scroll("outer").1 > 0.0, "{mode:?}");
|
|
||||||
// Far past the end: the inner pane clamps at its travel, the outer stays.
|
|
||||||
rig.send(wheel(over, (0.0, 100_000.0), WheelUnit::Units));
|
|
||||||
assert_eq!((rig.offset("inner"), rig.offset("outer")), (Some((0.0, inner_max.1)), None), "{mode:?}");
|
|
||||||
// At the end of travel the same wheel goes to the pane around it.
|
|
||||||
rig.send(wheel(over, (0.0, 16.0), WheelUnit::Units));
|
|
||||||
assert_eq!((rig.offset("inner"), rig.offset("outer")), (Some((0.0, inner_max.1)), Some((0.0, 16.0 * k))), "{mode:?}");
|
|
||||||
// The other way the inner pane has room, so it takes it and the outer holds.
|
|
||||||
rig.send(wheel(over, (0.0, -8.0), WheelUnit::Units));
|
|
||||||
assert_eq!(rig.offset("inner"), Some((0.0, inner_max.1 - 8.0 * k)), "{mode:?}");
|
|
||||||
assert_eq!(rig.offset("outer"), Some((0.0, 16.0 * k)), "{mode:?}");
|
|
||||||
// Back to the start, then further: clamps at zero and the outer takes the rest of the way back.
|
|
||||||
rig.send(wheel(over, (0.0, -100_000.0), WheelUnit::Units));
|
|
||||||
assert_eq!(rig.offset("inner"), Some((0.0, 0.0)), "{mode:?}");
|
|
||||||
rig.send(wheel(over, (0.0, -4.0), WheelUnit::Units));
|
|
||||||
assert_eq!(rig.offset("outer"), Some((0.0, 12.0 * k)), "{mode:?}");
|
|
||||||
// A wheel off every pane moves nothing; the horizontal axis has no travel here.
|
|
||||||
let before = (rig.offset("inner"), rig.offset("outer"));
|
|
||||||
rig.send(wheel((outer.x - 0.5, outer.y - 0.5), (0.0, 10.0), WheelUnit::Units));
|
|
||||||
rig.send(wheel(over, (10.0, 0.0), WheelUnit::Units));
|
|
||||||
assert_eq!((rig.offset("inner"), rig.offset("outer")), before, "{mode:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_wheel_line_is_one_cell_in_cells_and_the_body_text_size_in_pixels() {
|
|
||||||
let mut cells = Rig::new(Port::new(), &nested_surface(), (Metrics::Cells, 1.0));
|
|
||||||
cells.send(wheel(inside(cells.rect("inner")), (0.0, 3.0), WheelUnit::Lines));
|
|
||||||
assert_eq!(cells.offset("inner"), Some((0.0, 3.0)));
|
|
||||||
for scale in [1.0, 1.5] {
|
|
||||||
let mut pixels = Rig::new(Port::new(), &nested_surface(), (Metrics::Pixels, scale));
|
|
||||||
pixels.send(wheel(inside(pixels.rect("inner")), (0.0, 2.0), WheelUnit::Lines));
|
|
||||||
assert_eq!(pixels.offset("inner"), Some((0.0, 2.0 * 16.0 * scale)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_wheel_over_a_modal_never_scrolls_the_tree_beneath() {
|
|
||||||
let pane = column("pane", Some((160.0, 80.0)), Overflow::Scroll, vec![fixed("fill", 160.0, 400.0)]);
|
|
||||||
let document = surface(column("root", None, Overflow::Visible, vec![pane, overlay("modal", true, vec![fixed("dialog", 80.0, 48.0)])]), vec![decl("dismiss", &[])]);
|
|
||||||
for mode in MODES {
|
|
||||||
let mut rig = Rig::new(Port::new(), &document, mode);
|
|
||||||
rig.send(wheel(inside(rig.rect("pane")), (0.0, 16.0), WheelUnit::Units));
|
|
||||||
assert_eq!(rig.offset("pane"), None, "{mode:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ----- press semantics -----
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_press_released_elsewhere_or_with_another_button_or_after_a_cancel_activates_nothing() {
|
|
||||||
for mode in MODES {
|
|
||||||
let mut rig = Rig::new(Port::new(), &controls_surface(), mode);
|
|
||||||
let (a, b) = (inside(rig.rect("a")), inside(rig.rect("b")));
|
|
||||||
// Down on a, up on b.
|
|
||||||
rig.send(down(a));
|
|
||||||
rig.send(up(b));
|
|
||||||
// Secondary and middle buttons never press.
|
|
||||||
for button in [PointerButton::Secondary, PointerButton::Middle] {
|
|
||||||
rig.send(InputEvent::PointerDown { at: a, button, modifiers: mods() });
|
|
||||||
rig.send(InputEvent::PointerUp { at: a, button, modifiers: mods() });
|
|
||||||
}
|
|
||||||
// Down, the platform takes the pointer, a stray up.
|
|
||||||
rig.send(down(a));
|
|
||||||
rig.send(InputEvent::PointerCancel);
|
|
||||||
rig.send(up(a));
|
|
||||||
// An up with no press.
|
|
||||||
rig.send(up(a));
|
|
||||||
assert_eq!(rig.minted(), vec![], "{mode:?}");
|
|
||||||
// And the same button down and up mints once.
|
|
||||||
rig.click(a);
|
|
||||||
assert_eq!(commands_of(&rig.minted()), ["go"], "{mode:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_secondary_up_does_not_release_a_primary_press() {
|
|
||||||
let mut rig = Rig::new(Port::new(), &controls_surface(), MODES[0]);
|
|
||||||
let a = inside(rig.rect("a"));
|
|
||||||
rig.send(down(a));
|
|
||||||
rig.send(InputEvent::PointerUp { at: a, button: PointerButton::Secondary, modifiers: mods() });
|
|
||||||
assert_eq!(rig.minted(), vec![]);
|
|
||||||
rig.send(up(a));
|
|
||||||
assert_eq!(commands_of(&rig.minted()), ["go"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_busy_button_mints_once_however_often_it_is_pressed() {
|
|
||||||
for mode in MODES {
|
|
||||||
let mut rig = Rig::new(Port::new(), &controls_surface(), mode);
|
|
||||||
let a = inside(rig.rect("a"));
|
|
||||||
assert_eq!(rig.click(a), vec![]);
|
|
||||||
assert_eq!(rig.click(a), vec![], "{mode:?}: a busy press is silent, not a refusal");
|
|
||||||
assert_eq!(commands_of(&rig.minted()), ["go"], "{mode:?}");
|
|
||||||
// The user sees it: the busy button is drawn disabled.
|
|
||||||
rig.draw();
|
|
||||||
let disabled = Theme::std().colors["thing.control.disabled"].clone();
|
|
||||||
assert!(rig.rendered.commands.iter().any(|c| matches!(c, crate::render::RenderCommand::FillRect { color, .. } if *color == disabled)), "{mode:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_toggle_flips_its_draft_and_fires_on_change_once_per_press() {
|
|
||||||
for mode in MODES {
|
|
||||||
let mut rig = Rig::new(Port::new(), &controls_surface(), mode);
|
|
||||||
let flag = inside(rig.rect("flag"));
|
|
||||||
rig.click(flag);
|
|
||||||
let first = rig.minted();
|
|
||||||
assert_eq!(commands_of(&first), ["flip"], "{mode:?}");
|
|
||||||
assert_eq!(first[0].captured[0].value, InputValue::Bool(BoolValue { value: true }), "{mode:?}");
|
|
||||||
assert_eq!(rig.draft("flag"), Some(InputValue::Bool(BoolValue { value: true })));
|
|
||||||
// A second press is a change to a control with an invocation waiting: it is refused and says so, it
|
|
||||||
// fires nothing more, and it leaves the draft that was sent (a busy control holds no unsent value).
|
|
||||||
let said = rig.click(flag);
|
|
||||||
assert_eq!(said.iter().map(|d| (d.code, d.node.as_ref().map(NodeId::as_str))).collect::<Vec<_>>(), vec![(Code::ActivationBlocked, Some("flag"))], "{mode:?}");
|
|
||||||
assert_eq!(rig.minted(), vec![], "{mode:?}");
|
|
||||||
assert_eq!(rig.draft("flag"), Some(InputValue::Bool(BoolValue { value: true })), "{mode:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_slider_drag_writes_snapped_drafts_and_commits_once_wherever_it_is_released() {
|
|
||||||
for mode in MODES {
|
|
||||||
let mut rig = Rig::new(Port::new(), &controls_surface(), mode);
|
|
||||||
let track = rig.rect("level");
|
|
||||||
let along = |fraction: f32| (track.x + fraction * track.w, track.y + 0.5);
|
|
||||||
let value = |v: f64| Some(InputValue::Number(NumberValue { value: v }));
|
|
||||||
rig.send(down(along(0.34)));
|
|
||||||
assert_eq!(rig.draft("level"), value(30.0), "{mode:?}: 34 snaps to the step from min");
|
|
||||||
rig.send(mv(along(0.76)));
|
|
||||||
assert_eq!(rig.draft("level"), value(80.0), "{mode:?}");
|
|
||||||
// The drag is shown while it is made.
|
|
||||||
rig.draw();
|
|
||||||
let thumb = |rig: &Rig| rig.rendered.commands.iter().filter_map(|c| match c {
|
|
||||||
crate::render::RenderCommand::FillRect { rect, .. } if rect.w <= track.h.max(1.0) + 0.01 && rect.h > 0.0 => Some(rect.x),
|
|
||||||
_ => None,
|
|
||||||
}).last();
|
|
||||||
assert!(thumb(&rig).is_some());
|
|
||||||
// Released far outside the track, even outside the pane: one commit of the last draft.
|
|
||||||
rig.send(mv((track.x + track.w * 3.0, track.y + 500.0)));
|
|
||||||
assert_eq!(rig.draft("level"), value(100.0), "{mode:?}: past the end clamps");
|
|
||||||
rig.send(up((track.x - 900.0, track.y - 900.0)));
|
|
||||||
let minted = rig.minted();
|
|
||||||
assert_eq!(commands_of(&minted), ["set"], "{mode:?}");
|
|
||||||
assert_eq!(minted[0].captured[0].value, InputValue::Number(NumberValue { value: 100.0 }), "{mode:?}");
|
|
||||||
// Moving after the up changes nothing.
|
|
||||||
rig.send(mv(along(0.1)));
|
|
||||||
assert_eq!(rig.draft("level"), value(100.0), "{mode:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_cancelled_slider_press_leaves_the_draft_it_found_and_fires_nothing() {
|
|
||||||
for mode in MODES {
|
|
||||||
let mut rig = Rig::new(Port::new(), &controls_surface(), mode);
|
|
||||||
let track = rig.rect("level");
|
|
||||||
let along = |fraction: f32| (track.x + fraction * track.w, track.y + 0.5);
|
|
||||||
// No draft before: a press then a cancel leaves none, and a stray up commits nothing.
|
|
||||||
rig.send(down(along(0.5)));
|
|
||||||
assert!(rig.draft("level").is_some());
|
|
||||||
rig.send(InputEvent::PointerCancel);
|
|
||||||
rig.send(up(along(0.5)));
|
|
||||||
assert_eq!((rig.draft("level"), rig.minted()), (None, vec![]), "{mode:?}");
|
|
||||||
// A draft that is already waiting on a result comes back as it was.
|
|
||||||
rig.send(down(along(0.3)));
|
|
||||||
rig.send(up(along(0.3)));
|
|
||||||
assert_eq!(commands_of(&rig.minted()), ["set"]);
|
|
||||||
let held = rig.draft("level");
|
|
||||||
rig.send(down(along(0.9)));
|
|
||||||
rig.send(mv(along(0.2)));
|
|
||||||
rig.send(InputEvent::PointerCancel);
|
|
||||||
assert_eq!((rig.draft("level"), rig.minted()), (held, vec![]), "{mode:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_press_on_a_select_or_a_text_input_does_nothing_yet() {
|
|
||||||
for mode in MODES {
|
|
||||||
let mut rig = Rig::new(Port::new(), &fields_surface(), mode);
|
|
||||||
for id in ["field", "choice"] {
|
|
||||||
assert_eq!(rig.click(inside(rig.rect(id))), vec![], "{mode:?} {id}");
|
|
||||||
}
|
|
||||||
assert_eq!((rig.minted(), rig.drafts.is_empty()), (vec![], true), "{mode:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_click_while_a_command_waits_for_confirmation_is_a_refusal_the_event_returns() {
|
|
||||||
for mode in MODES {
|
|
||||||
let mut document = surface(column("root", None, Overflow::Visible, vec![button("a", "ask", 160.0, 48.0), button("b", "go", 160.0, 48.0)]), vec![decl("ask", &[]), decl("go", &[])]);
|
|
||||||
document.commands[0].confirm = Some("Sure?".into());
|
|
||||||
let mut rig = Rig::new(Port::new(), &document, mode);
|
|
||||||
assert_eq!(rig.click(inside(rig.rect("a"))), vec![]);
|
|
||||||
assert!(rig.commands.confirming().is_some() && rig.minted().is_empty(), "{mode:?}");
|
|
||||||
let said = rig.click(inside(rig.rect("b")));
|
|
||||||
assert_eq!(said.iter().map(|d| d.code).collect::<Vec<_>>(), vec![Code::ActivationBlocked], "{mode:?}");
|
|
||||||
assert_eq!(said[0].node.as_ref().map(NodeId::as_str), Some("b"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ----- a control that takes no change holds no unsent value -----
|
|
||||||
|
|
||||||
fn result_change(sent: &CommandInvocation, clear: bool) -> Change {
|
|
||||||
let result = CommandResult::completed(sent, seq(1), None, clear, None);
|
|
||||||
let address = Address { provider: ProviderId::new(PROVIDER), schema: SchemaId::new(CommandResult::SCHEMA_NAME), key: RecordKey::new(result.record_key()) };
|
|
||||||
Change::Upsert(Entry { address, record: Record::Result(result) })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn refusals(said: &[Diagnostic]) -> Vec<(Code, Option<&str>)> {
|
|
||||||
said.iter().map(|d| (d.code, d.node.as_ref().map(NodeId::as_str))).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_slider_that_waits_for_its_result_takes_no_press_or_drag_and_a_completion_leaves_no_stray_draft() {
|
|
||||||
for mode in MODES {
|
|
||||||
let mut rig = Rig::new(Port::new(), &controls_surface(), mode);
|
|
||||||
let track = rig.rect("level");
|
|
||||||
let along = |fraction: f32| (track.x + fraction * track.w, track.y + 0.5);
|
|
||||||
let value = |v: f64| Some(InputValue::Number(NumberValue { value: v }));
|
|
||||||
rig.send(down(along(0.3)));
|
|
||||||
rig.send(up(along(0.3)));
|
|
||||||
let sent = rig.minted().remove(0);
|
|
||||||
assert_eq!(rig.draft("level"), value(30.0), "{mode:?}");
|
|
||||||
// The slider waits: a second press and its drag are refused, say so, and write nothing.
|
|
||||||
assert_eq!(refusals(&rig.send(down(along(0.8)))), vec![(Code::ActivationBlocked, Some("level"))], "{mode:?}");
|
|
||||||
assert_eq!(rig.draft("level"), value(30.0), "{mode:?}: the press wrote nothing");
|
|
||||||
rig.send(mv(along(0.9)));
|
|
||||||
assert_eq!(rig.draft("level"), value(30.0), "{mode:?}: a refused press starts no drag");
|
|
||||||
assert_eq!(rig.send(up(along(0.9))), vec![], "{mode:?}");
|
|
||||||
assert_eq!(rig.minted(), vec![], "{mode:?}");
|
|
||||||
// The result clears the draft that was sent, and nothing else is left drawn on the slider.
|
|
||||||
let tree = &rig.tree;
|
|
||||||
rig.commands.apply(&result_change(&sent, true), Timestamp(5), &|_| Some(tree), &mut rig.drafts, &mut rig.state, &mut rig.ledger);
|
|
||||||
assert_eq!(rig.draft("level"), None, "{mode:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_toggle_pressed_while_it_waits_is_refused_and_a_completion_leaves_the_provider_true() {
|
|
||||||
for mode in MODES {
|
|
||||||
let mut rig = Rig::new(Port::new(), &controls_surface(), mode);
|
|
||||||
let flag = inside(rig.rect("flag"));
|
|
||||||
rig.click(flag);
|
|
||||||
let sent = rig.minted().remove(0);
|
|
||||||
assert_eq!(refusals(&rig.click(flag)), vec![(Code::ActivationBlocked, Some("flag"))], "{mode:?}");
|
|
||||||
let tree = &rig.tree;
|
|
||||||
rig.commands.apply(&result_change(&sent, true), Timestamp(5), &|_| Some(tree), &mut rig.drafts, &mut rig.state, &mut rig.ledger);
|
|
||||||
assert_eq!(rig.draft("flag"), None, "{mode:?}: nothing survives to show a checked box the provider does not hold");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_slider_press_while_a_command_waits_for_confirmation_writes_no_draft() {
|
|
||||||
for mode in MODES {
|
|
||||||
let mut document = controls_surface();
|
|
||||||
document.commands.iter_mut().find(|c| c.id.as_str() == "go").unwrap().confirm = Some("Sure?".into());
|
|
||||||
let mut rig = Rig::new(Port::new(), &document, mode);
|
|
||||||
rig.click(inside(rig.rect("a")));
|
|
||||||
assert!(rig.commands.confirming().is_some(), "{mode:?}");
|
|
||||||
let track = rig.rect("level");
|
|
||||||
let said = rig.send(down((track.x + 0.5 * track.w, track.y + 0.5)));
|
|
||||||
assert_eq!(refusals(&said), vec![(Code::ActivationBlocked, Some("level"))], "{mode:?}");
|
|
||||||
assert_eq!((rig.draft("level"), rig.drafts.is_empty()), (None, true), "{mode:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn input_other_than_the_pointer_changes_nothing() {
|
|
||||||
let mut rig = Rig::new(Port::new(), &controls_surface(), MODES[0]);
|
|
||||||
let before = (rig.rendered.clone(), rig.drafts.len());
|
|
||||||
for event in [
|
|
||||||
InputEvent::Key { key: crate::input::Key::Enter, modifiers: mods(), repeat: false },
|
|
||||||
InputEvent::Text("x".into()),
|
|
||||||
InputEvent::Compose { text: "か".into(), cursor: None },
|
|
||||||
InputEvent::Focus(true),
|
|
||||||
] {
|
|
||||||
assert_eq!(rig.send(event), vec![]);
|
|
||||||
}
|
|
||||||
assert_eq!((rig.minted(), rig.drafts.len()), (vec![], before.1));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_slider_snaps_from_its_own_minimum_and_follows_its_own_track() {
|
|
||||||
for mode in MODES {
|
|
||||||
let mut rig = Rig::new(Port::new(), &lone_slider(20.0, 120.0, 10.0), mode);
|
|
||||||
let track = rig.rect("level");
|
|
||||||
assert!(track.x > 0.0, "{mode:?}: the track does not start at the root's edge");
|
|
||||||
let along = |fraction: f32| (track.x + fraction * track.w, track.y + 0.5);
|
|
||||||
let value = |v: f64| Some(InputValue::Number(NumberValue { value: v }));
|
|
||||||
rig.send(down(along(0.0)));
|
|
||||||
assert_eq!(rig.draft("level"), value(20.0), "{mode:?}: the track's left edge is the minimum");
|
|
||||||
rig.send(mv(along(0.47)));
|
|
||||||
assert_eq!(rig.draft("level"), value(70.0), "{mode:?}: 20 + 47 = 67 snaps to 70 from 20");
|
|
||||||
rig.send(mv(along(1.0)));
|
|
||||||
assert_eq!(rig.draft("level"), value(120.0), "{mode:?}");
|
|
||||||
// A move that is not a position is not a value.
|
|
||||||
rig.send(mv((f32::NAN, track.y)));
|
|
||||||
assert_eq!(rig.draft("level"), value(120.0), "{mode:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_track_that_shrinks_to_nothing_mid_drag_leaves_the_draft_as_it_was() {
|
|
||||||
for mode in MODES {
|
|
||||||
let mut rig = Rig::new(Port::new(), &controls_surface(), mode);
|
|
||||||
let track = rig.rect("level");
|
|
||||||
let value = |v: f64| Some(InputValue::Number(NumberValue { value: v }));
|
|
||||||
rig.send(down((track.x + 0.5 * track.w, track.y + 0.5)));
|
|
||||||
assert_eq!(rig.draft("level"), value(50.0), "{mode:?}");
|
|
||||||
// The surface shrinks under the pointer: the slider's rect is now zero wide.
|
|
||||||
for placed in rig.rendered.placed.iter_mut().filter(|placed| placed.id.as_str() == "level") {
|
|
||||||
placed.rect.w = 0.0;
|
|
||||||
}
|
|
||||||
// At the track's left edge (0 over 0) and past it (n over 0): neither is a value.
|
|
||||||
for x in [track.x, track.x + 10.0] {
|
|
||||||
rig.send(mv((x, track.y + 0.5)));
|
|
||||||
assert_eq!(rig.draft("level"), value(50.0), "{mode:?}: a move over a zero-width track at {x}");
|
|
||||||
}
|
|
||||||
rig.send(up((track.x, track.y)));
|
|
||||||
let minted = rig.minted();
|
|
||||||
assert_eq!(minted.len(), 1, "{mode:?}");
|
|
||||||
assert_eq!(minted[0].captured[0].value, InputValue::Number(NumberValue { value: 50.0 }), "{mode:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_slider_with_no_range_or_a_step_of_zero_is_handled_by_what_it_declares() {
|
|
||||||
for mode in MODES {
|
|
||||||
for (min, max) in [(5.0, 5.0), (0.0, f64::INFINITY), (9.0, 3.0)] {
|
|
||||||
let mut rig = Rig::new(Port::new(), &lone_slider(min, max, 1.0), mode);
|
|
||||||
let at = inside(rig.rect("level"));
|
|
||||||
rig.click(at);
|
|
||||||
assert_eq!((rig.draft("level"), rig.minted()), (None, vec![]), "{mode:?} {min}..{max}");
|
|
||||||
}
|
|
||||||
// No step: the raw position, unsnapped.
|
|
||||||
let mut rig = Rig::new(Port::new(), &lone_slider(0.0, 100.0, 0.0), mode);
|
|
||||||
let track = rig.rect("level");
|
|
||||||
rig.send(down((track.x + 0.25 * track.w, track.y + 0.5)));
|
|
||||||
assert_eq!(rig.draft("level"), Some(InputValue::Number(NumberValue { value: 25.0 })), "{mode:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_press_on_a_text_input_or_a_select_does_not_fall_through_to_the_button_around_it() {
|
|
||||||
let (input, select) = fields();
|
|
||||||
let card = Node::Button(ButtonNode {
|
|
||||||
common: common("card"),
|
|
||||||
content: vec![fixed("pad", 160.0, 16.0), input, select],
|
|
||||||
on_activate: command("go"),
|
|
||||||
enabled: lit_bool(true),
|
|
||||||
});
|
|
||||||
for mode in MODES {
|
|
||||||
let document = surface(column("root", None, Overflow::Visible, vec![card.clone()]), vec![decl("go", &[])]);
|
|
||||||
let mut rig = Rig::new(Port::new(), &document, mode);
|
|
||||||
for id in ["field", "choice"] {
|
|
||||||
let r = rig.rect(id);
|
|
||||||
assert!(r.w >= 1.0 && r.h >= 1.0, "{mode:?} {id}");
|
|
||||||
assert_eq!(rig.click(inside(r)), vec![], "{mode:?} {id}");
|
|
||||||
}
|
|
||||||
assert_eq!(rig.minted(), vec![], "{mode:?}: the card around them was not pressed");
|
|
||||||
// The card itself still is.
|
|
||||||
rig.click(inside(rig.rect("pad")));
|
|
||||||
assert_eq!(commands_of(&rig.minted()), ["go"], "{mode:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_wheel_that_is_not_a_number_or_runs_on_a_bad_scale_is_ignored_or_taken_at_one() {
|
|
||||||
let mut rig = Rig::new(Port::new(), &nested_surface(), (Metrics::Pixels, 1.5));
|
|
||||||
let over = inside(rig.rect("inner"));
|
|
||||||
// The scale the host gave is not usable: the offset is the wheel's units as they are.
|
|
||||||
for bad in [0.0, f32::INFINITY, f32::NAN, -2.0] {
|
|
||||||
rig.scroll = ScrollOffsets::default();
|
|
||||||
rig.scale = bad;
|
|
||||||
rig.send(wheel(over, (0.0, 10.0), WheelUnit::Units));
|
|
||||||
assert_eq!(rig.offset("inner"), Some((0.0, 10.0)), "scale {bad}");
|
|
||||||
}
|
|
||||||
// A delta that is not a number moves nothing, and does not reset what is scrolled.
|
|
||||||
rig.scale = 1.5;
|
|
||||||
rig.scroll.set(nid("inner"), (0.0, 30.0));
|
|
||||||
for bad in [f32::NAN, f32::INFINITY] {
|
|
||||||
rig.send(wheel(over, (0.0, bad), WheelUnit::Units));
|
|
||||||
rig.send(wheel(over, (bad, 0.0), WheelUnit::Units));
|
|
||||||
assert_eq!(rig.offset("inner"), Some((0.0, 30.0)), "delta {bad}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_wheel_scrolls_the_horizontal_axis_by_its_own_delta() {
|
|
||||||
let pane = column("pane", Some((160.0, 80.0)), Overflow::Scroll, vec![fixed("wide", 400.0, 400.0)]);
|
|
||||||
let document = surface(column("root", None, Overflow::Visible, vec![pane]), vec![]);
|
|
||||||
for mode in MODES {
|
|
||||||
let mut rig = Rig::new(Port::new(), &document, mode);
|
|
||||||
let k = if mode.0 == Metrics::Pixels { mode.1 } else { 1.0 };
|
|
||||||
let over = inside(rig.rect("pane"));
|
|
||||||
assert!(rig.max_scroll("pane").0 > 0.0 && rig.max_scroll("pane").1 > 0.0, "{mode:?}");
|
|
||||||
rig.send(wheel(over, (8.0, 4.0), WheelUnit::Units));
|
|
||||||
assert_eq!(rig.offset("pane"), Some((8.0 * k, 4.0 * k)), "{mode:?}");
|
|
||||||
rig.send(wheel(over, (-2.0, 0.0), WheelUnit::Units));
|
|
||||||
assert_eq!(rig.offset("pane"), Some((6.0 * k, 4.0 * k)), "{mode:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,255 +0,0 @@
|
||||||
//! The Measure seam: what a leaf's intrinsic size is. Text, controls and images are sized by a
|
|
||||||
//! `Measure` the frame owner composes (cut 9a ships Pixels and Cells); layout never estimates
|
|
||||||
//! them. Taffy's own types stop at this file: `Leaf` and `Constraint` are plain data.
|
|
||||||
|
|
||||||
use taffy::{AvailableSpace, Size};
|
|
||||||
use thing_contract::NodeId;
|
|
||||||
|
|
||||||
use crate::bind::Bound;
|
|
||||||
use super::ControlForm;
|
|
||||||
use crate::text::CellText;
|
|
||||||
|
|
||||||
/// The room a leaf is offered on one axis.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
||||||
pub enum Avail {
|
|
||||||
Definite(f32),
|
|
||||||
MinContent,
|
|
||||||
MaxContent,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What a leaf is asked, in logical px (Pixels) or cells (Cells). `known` is a size the parent
|
|
||||||
/// already fixed on an axis; `available` is the room on each axis, `[width, height]`.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
||||||
pub struct Constraint {
|
|
||||||
pub known: [Option<f32>; 2],
|
|
||||||
pub available: [Avail; 2],
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A leaf node with the values it shows, borrowed from the bound tree.
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
pub enum Leaf<'a> {
|
|
||||||
Text { node: &'a NodeId, content: &'a Bound, style_token: &'a str, wrap: bool, max_lines: Option<u32> },
|
|
||||||
TextInput { node: &'a NodeId, multiline: bool, placeholder: &'a Bound, value: &'a Bound },
|
|
||||||
Toggle { node: &'a NodeId },
|
|
||||||
Slider { node: &'a NodeId },
|
|
||||||
Select { node: &'a NodeId, selected: &'a Bound },
|
|
||||||
Image { node: &'a NodeId, asset: &'a Bound },
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A face the text engine drew with. Opaque to core: the backend maps it to its own font.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub struct FontId(pub u32);
|
|
||||||
|
|
||||||
/// One placed glyph of a line: the engine's glyph id and its position in the line, logical px.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
||||||
pub struct Glyph {
|
|
||||||
pub id: u32,
|
|
||||||
pub x: f32,
|
|
||||||
pub y: f32,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
|
||||||
pub struct CellStyle {
|
|
||||||
pub bold: bool,
|
|
||||||
pub italic: bool,
|
|
||||||
pub underline: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What one line of text is made of: shaped glyphs (Pixels) or characters (Cells).
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub enum Run {
|
|
||||||
Glyphs { font: FontId, size: f32, glyphs: Vec<Glyph> },
|
|
||||||
Cells { text: CellText, style: CellStyle },
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The Text leaf a line breaker is asked to lay out.
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
pub struct TextRequest<'a> {
|
|
||||||
pub node: &'a NodeId,
|
|
||||||
pub text: &'a str,
|
|
||||||
pub style_token: &'a str,
|
|
||||||
pub wrap: bool,
|
|
||||||
pub max_lines: Option<u32>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One line: `y` and `height` are measured from the top of the node, in logical px or cells.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct TextLine {
|
|
||||||
pub y: f32,
|
|
||||||
pub height: f32,
|
|
||||||
pub run: Run,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq)]
|
|
||||||
pub struct TextLayout {
|
|
||||||
pub lines: Vec<TextLine>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The intrinsic size `(width, height)` of a leaf under a constraint. A non-finite or negative
|
|
||||||
/// answer is taken as zero. `text` is the same engine's answer for a Text leaf at its final
|
|
||||||
/// width: the lines `measure` sized the leaf for, broken and shaped. Wrap and `max_lines` are the
|
|
||||||
/// engine's; render never breaks a line.
|
|
||||||
pub trait Measure {
|
|
||||||
fn measure(&mut self, leaf: &Leaf, constraint: Constraint) -> (f32, f32);
|
|
||||||
fn text(&mut self, request: &TextRequest, width: f32) -> TextLayout;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The largest length, in device px or cells, a style or a measure may state: 2^21 = 2,097,152.
|
|
||||||
/// f32 has 24 mantissa bits, so a coordinate below 2^24 is exact to a whole pixel and one below
|
|
||||||
/// 2^21 keeps 3 fractional bits, 1/8 px. A coordinate is a sum of lengths along an axis: eight
|
|
||||||
/// maximal siblings still sum below 2^24 (whole-pixel exact), and any run of siblings whose
|
|
||||||
/// extents sum below 2^21 keeps 1/8 px. A length beyond the bound is an invalid style value and a
|
|
||||||
/// larger measured size is clamped to it.
|
|
||||||
pub(crate) const MAX_DEVICE: f32 = 2_097_152.0;
|
|
||||||
|
|
||||||
/// The smallest nonzero extent a measure may state: 1/8 px, the precision the length bound
|
|
||||||
/// leaves. A smaller side is below the resolution layout keeps.
|
|
||||||
pub(super) const MIN_SIDE: f32 = 0.125;
|
|
||||||
|
|
||||||
/// The fewest rows a Cells control needs to be `Bordered`: a border row above and below a content row.
|
|
||||||
pub(super) const BORDERED_ROWS: f32 = 3.0;
|
|
||||||
|
|
||||||
/// Device px per cell, `(across, down)`: the metric a terminal cell stands for. In Cells mode a Px
|
|
||||||
/// length converts at it (8 wide, 16 tall), and an Image's pixel extent is read in cells at it.
|
|
||||||
pub(crate) const CELL_PX: (f32, f32) = (8.0, 16.0);
|
|
||||||
|
|
||||||
/// The axis a Px length runs along: across (width, left and right, columns) or down (height, top
|
|
||||||
/// and bottom, rows). A cell is not square, so a Px length converts per axis in Cells.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub(super) enum Axis {
|
|
||||||
X,
|
|
||||||
Y,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The one place logical units become device units and back: `k` device px per logical px
|
|
||||||
/// (1 in Cells, where `length` divides a Px length by the cell metric instead). Everything past
|
|
||||||
/// this adapter, the style map and the solver included, is device.
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
pub(super) struct Device {
|
|
||||||
k: f32,
|
|
||||||
cells: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Device {
|
|
||||||
pub(super) fn new(k: f32, cells: bool) -> Self {
|
|
||||||
Self { k, cells }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The least a Use placeholder takes, so its error is visible: 16 logical px each way.
|
|
||||||
pub(super) fn placeholder(self) -> (f32, f32) {
|
|
||||||
(self.length(16.0, Axis::X), self.length(16.0, Axis::Y))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether this is a cell grid.
|
|
||||||
pub(super) fn cells(self) -> bool {
|
|
||||||
self.cells
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A Plot's size: the CSS default object size, 300x150 logical px. A plot is sized by layout,
|
|
||||||
/// never measured.
|
|
||||||
pub(super) fn plot(self) -> (f32, f32) {
|
|
||||||
(self.length(300.0, Axis::X), self.length(150.0, Axis::Y))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A viewport side or a measured size in device units: logical px times the scale, or cells
|
|
||||||
/// as they are (a Measure answers in cells in Cells).
|
|
||||||
pub(super) fn px(self, logical: f32) -> f32 {
|
|
||||||
logical * self.k
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A Px length of the document in device units along `axis`: times the scale in Pixels, divided
|
|
||||||
/// by the cell metric in Cells. Taffy's rounding then lands it on a device pixel or a cell.
|
|
||||||
pub(super) fn length(self, px: f32, axis: Axis) -> f32 {
|
|
||||||
if self.cells {
|
|
||||||
px / match axis {
|
|
||||||
Axis::X => CELL_PX.0,
|
|
||||||
Axis::Y => CELL_PX.1,
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
px * self.k
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A border side of `px` along `axis`: its Px length, and in Cells at least one cell when it is
|
|
||||||
/// nonzero, so the terminal shows the border and content never sits under it. Zero stays zero.
|
|
||||||
pub(super) fn border(self, px: f32, axis: Axis) -> f32 {
|
|
||||||
let length = self.length(px, axis);
|
|
||||||
if self.cells && px > 0.0 { length.max(1.0) } else { length }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A control's form, read off its laid border-box height `h` and the laid height `row` of its
|
|
||||||
/// content node, never fed back to the solve: in Pixels always `Bordered`; in Cells `Bordered`
|
|
||||||
/// from `BORDERED_ROWS` rows and only when the content row fits between the border rows, else
|
|
||||||
/// `Compact` (ruling cells-bordered-needs-content-fit).
|
|
||||||
pub(super) fn form(self, h: f32, row: f32) -> ControlForm {
|
|
||||||
let (_, edge) = self.inset(ControlForm::Bordered, f32::INFINITY, f32::INFINITY);
|
|
||||||
if !self.cells || (h >= BORDERED_ROWS && row + 2.0 * edge <= h) { ControlForm::Bordered } else { ControlForm::Compact }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The inset of a laid control's content from its border box, `(x, y)`, in device units: the one
|
|
||||||
/// rule, owned here. In Pixels: the 2 px of chrome. In Cells a `Bordered` control keeps one cell
|
|
||||||
/// clear on every side, a `Compact` one a cell on each side across and none down. Never more than
|
|
||||||
/// half a side.
|
|
||||||
pub(super) fn inset(self, form: ControlForm, w: f32, h: f32) -> (f32, f32) {
|
|
||||||
let (x, y) = match (self.cells, form) {
|
|
||||||
(false, _) => (self.px(2.0), self.px(2.0)),
|
|
||||||
(true, ControlForm::Bordered) => (1.0, 1.0),
|
|
||||||
(true, ControlForm::Compact) => (1.0, 0.0),
|
|
||||||
};
|
|
||||||
(x.min(w / 2.0).max(0.0), y.min(h / 2.0).max(0.0))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn logical(self, device: f32) -> f32 {
|
|
||||||
device / self.k
|
|
||||||
}
|
|
||||||
|
|
||||||
fn avail(self, space: AvailableSpace) -> Avail {
|
|
||||||
match space {
|
|
||||||
AvailableSpace::Definite(v) => Avail::Definite(self.logical(v)),
|
|
||||||
AvailableSpace::MinContent => Avail::MinContent,
|
|
||||||
AvailableSpace::MaxContent => Avail::MaxContent,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A measure's answer as a device size: non-finite or negative is zero, huge is the bound.
|
|
||||||
fn size(self, (w, h): (f32, f32)) -> Size<f32> {
|
|
||||||
let side = |v: f32| if v.is_finite() && v > 0.0 { self.px(v).min(MAX_DEVICE) } else { 0.0 };
|
|
||||||
Size { width: side(w), height: side(h) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Taffy's leaf callback to `Measure`: device px in, logical out, and back.
|
|
||||||
pub(super) fn measure_leaf(
|
|
||||||
measure: &mut dyn Measure,
|
|
||||||
leaf: &Leaf,
|
|
||||||
dev: Device,
|
|
||||||
known: Size<Option<f32>>,
|
|
||||||
space: Size<AvailableSpace>,
|
|
||||||
) -> Size<f32> {
|
|
||||||
let constraint = Constraint {
|
|
||||||
known: [known.width.map(|v| dev.logical(v)), known.height.map(|v| dev.logical(v))],
|
|
||||||
available: [dev.avail(space.width), dev.avail(space.height)],
|
|
||||||
};
|
|
||||||
dev.size(measure.measure(leaf, constraint))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The aspect ratio an Image keeps when stretched, from what its measure says unconstrained
|
|
||||||
/// (logical px, judged in device px). `Ok(None)` is no extent at all (0x0: nothing known yet).
|
|
||||||
/// Each side must be 0 or within [MIN_SIDE, MAX_DEVICE] and not just one of them zero; the ratio
|
|
||||||
/// is then within [MIN_SIDE / MAX_DEVICE, MAX_DEVICE / MIN_SIDE] = [2^-24, 2^24] by derivation, so
|
|
||||||
/// no second range is checked. Anything else is an invalid measure: `Err`. A side the image takes
|
|
||||||
/// from its ratio is held under MAX_DEVICE by the image's own max size (see the walk).
|
|
||||||
pub(super) fn intrinsic_ratio(measure: &mut dyn Measure, leaf: &Leaf, dev: Device) -> Result<Option<f32>, ()> {
|
|
||||||
let constraint = Constraint { known: [None, None], available: [Avail::MaxContent, Avail::MaxContent] };
|
|
||||||
let (w, h) = measure.measure(leaf, constraint);
|
|
||||||
let (w, h) = (dev.px(w), dev.px(h));
|
|
||||||
let legal = |v: f32| v == 0.0 || (v.is_finite() && (MIN_SIDE..=MAX_DEVICE).contains(&v));
|
|
||||||
if !legal(w) || !legal(h) {
|
|
||||||
return Err(());
|
|
||||||
}
|
|
||||||
match (w == 0.0, h == 0.0) {
|
|
||||||
(true, true) => Ok(None),
|
|
||||||
(false, false) => Ok(Some(w / h)),
|
|
||||||
_ => Err(()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,264 +0,0 @@
|
||||||
//! Layout: a `BoundTree` and a `LayoutFrame` become the geometry of every node, solved by Taffy
|
|
||||||
//! (the one solver) and handed back as plain rectangles. A pure function: it reads no port, no
|
|
||||||
//! clock and no state, builds a fresh Taffy tree per call and keeps none.
|
|
||||||
//!
|
|
||||||
//! Pixels mode runs the solver in device pixels (every Px length and every measured size is
|
|
||||||
//! multiplied by the scale factor at the one adapter) with Taffy's cumulative rounding, so every
|
|
||||||
//! edge lands on a device pixel and adjacent boxes share it. Cells mode ignores the scale and converts a Px length at the cell metric (8x16 device px per cell). The
|
|
||||||
//! viewport is a block container the document root flows in, and is not itself in the output.
|
|
||||||
//! Overlays are out of flow: after the main pass each is laid out as its own root against its anchor
|
|
||||||
//! and appended after every main-tree node.
|
|
||||||
|
|
||||||
mod measure;
|
|
||||||
mod overlay;
|
|
||||||
mod style;
|
|
||||||
mod tree;
|
|
||||||
|
|
||||||
use taffy::{AvailableSpace, Size, compute_leaf_layout};
|
|
||||||
use measure::Device;
|
|
||||||
use thing_contract::{NodeId, OverlayNode};
|
|
||||||
|
|
||||||
pub use measure::{Avail, CellStyle, Constraint, FontId, Glyph, Leaf, Measure, Run, TextLayout, TextLine, TextRequest};
|
|
||||||
pub(crate) use measure::{CELL_PX, MAX_DEVICE};
|
|
||||||
|
|
||||||
use crate::bind::BoundTree;
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
|
|
||||||
/// The stack one level of nesting takes inside Taffy's recursion, worst of Flex, Grid, Block and
|
|
||||||
/// scroll boxes, measured in a debug build by `stack_per_level` in tests/layout.rs, doubled.
|
|
||||||
/// Taffy recurses natively and nothing in it can be wrapped per level, so the walk's depth is
|
|
||||||
/// known first and the one segment is sized for it.
|
|
||||||
const STACK_PER_LEVEL: usize = 96 * 1024;
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub enum Metrics {
|
|
||||||
Pixels,
|
|
||||||
Cells,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The room one layout fills. `viewport` is logical px (Pixels) or cells (Cells); `scale` is the
|
|
||||||
/// device pixels per logical px and is ignored in Cells.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
||||||
pub struct LayoutFrame {
|
|
||||||
pub viewport: (f32, f32),
|
|
||||||
pub scale: f32,
|
|
||||||
pub metrics: Metrics,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
||||||
pub struct Rect {
|
|
||||||
pub x: f32,
|
|
||||||
pub y: f32,
|
|
||||||
pub w: f32,
|
|
||||||
pub h: f32,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One node's geometry. `rect` is the absolute border box in device px (Pixels) or cells, and is
|
|
||||||
/// unscrolled. `parent` indexes the nearest laid ancestor in `LaidTree.nodes` (none for the
|
|
||||||
/// document root and every overlay root). `content` is the scrollable content size of an
|
|
||||||
/// `Overflow::Scroll` node; `clip` is the padding box (the border box inset by the laid border)
|
|
||||||
/// of a Clip or Scroll node.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct LaidNode {
|
|
||||||
pub id: NodeId,
|
|
||||||
pub parent: Option<u32>,
|
|
||||||
pub rect: Rect,
|
|
||||||
pub content: Option<(f32, f32)>,
|
|
||||||
/// How far `content` reaches past the padding box, never negative: the furthest the content
|
|
||||||
/// may scroll. Input clamps its position here; render and hit-test translate the children by
|
|
||||||
/// it. Layout never sees a scroll position, so a scroll never re-runs layout.
|
|
||||||
pub max_scroll: Option<(f32, f32)>,
|
|
||||||
pub clip: Option<Rect>,
|
|
||||||
/// A control's (Button, TextInput, Select, Toggle) form and content box, stated by layout; render
|
|
||||||
/// draws what this says and infers nothing from geometry. `None` for every other node.
|
|
||||||
pub control: Option<LaidControl>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The two forms of a control. In Pixels every control is `Bordered` (render draws chrome behind its
|
|
||||||
/// content). In Cells a control laid 3 rows or taller is `Bordered`: its border stands in the edge
|
|
||||||
/// cells and its content keeps one cell clear on every side. A control laid shorter is `Compact`: its
|
|
||||||
/// one-row affordance on the first row, one cell each side.
|
|
||||||
///
|
|
||||||
/// The form is a function of the laid border-box height alone (`Device::form`), read after the one
|
|
||||||
/// solve. A content-sized control is at least 3 rows because its border rows are in its max-content
|
|
||||||
/// height, not its min-content height: a short container still squeezes it to one compact row.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub enum ControlForm {
|
|
||||||
Bordered,
|
|
||||||
Compact,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A laid control: the form layout chose and the box its content is laid or drawn in, in device px
|
|
||||||
/// (Pixels) or cells: the border box less the form's inset. A Pixels Button's content is laid
|
|
||||||
/// without an inset, so its content box is its border box. `Compact` is the form of a control whose
|
|
||||||
/// content row does not fit between the border rows: its content stands from the first row and runs
|
|
||||||
/// past the last, so a painter clips a `Compact` control to its rect.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
||||||
pub struct LaidControl {
|
|
||||||
pub form: ControlForm,
|
|
||||||
pub content: Rect,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every laid node in paint order (document order, Repeat instances spliced), and the style
|
|
||||||
/// values that were not legal.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct LaidTree {
|
|
||||||
pub nodes: Vec<LaidNode>,
|
|
||||||
pub diagnostics: Vec<Diagnostic>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whole numbers stay whole, and negative zero is written as zero.
|
|
||||||
fn clean(v: f32) -> f32 {
|
|
||||||
if v == 0.0 || !v.is_finite() { 0.0 } else { v }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Why a frame was refused: nothing is laid out in a room that is not a finite positive size.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub enum FrameError {
|
|
||||||
/// The scale is not finite, not positive or past 1024 (Pixels only).
|
|
||||||
Scale,
|
|
||||||
/// A viewport side is not finite, not positive or past the length bound.
|
|
||||||
Viewport,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Why no layout came back. The frame owner keeps the last good `LaidTree` on either and shows
|
|
||||||
/// the diagnostic of `OutOfRange` (code `LayoutOutOfRange`, naming the first offending node in
|
|
||||||
/// document order).
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub enum LayoutError {
|
|
||||||
Frame(FrameError),
|
|
||||||
OutOfRange(Diagnostic),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<FrameError> for LayoutError {
|
|
||||||
fn from(error: FrameError) -> Self {
|
|
||||||
LayoutError::Frame(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn layout(tree: &BoundTree, frame: &LayoutFrame, measure: &mut dyn Measure) -> Result<LaidTree, LayoutError> {
|
|
||||||
let k = match frame.metrics {
|
|
||||||
Metrics::Cells => 1.0,
|
|
||||||
Metrics::Pixels if frame.scale.is_finite() && frame.scale > 0.0 && frame.scale <= 1024.0 => frame.scale,
|
|
||||||
Metrics::Pixels => return Err(FrameError::Scale.into()),
|
|
||||||
};
|
|
||||||
let dev = Device::new(k, frame.metrics == Metrics::Cells);
|
|
||||||
let side = |v: f32| (v.is_finite() && v > 0.0 && dev.px(v) <= MAX_DEVICE).then(|| dev.px(v));
|
|
||||||
let (Some(vw), Some(vh)) = (side(frame.viewport.0), side(frame.viewport.1)) else {
|
|
||||||
return Err(FrameError::Viewport.into());
|
|
||||||
};
|
|
||||||
let mut nodes = Vec::new();
|
|
||||||
let mut diagnostics = Vec::new();
|
|
||||||
let overlays = solve(tree, tree::Top::Document, dev, (vw, vh), (0.0, 0.0), measure, &mut nodes, &mut diagnostics)?;
|
|
||||||
overlay::place_all(tree, dev, (vw, vh), overlays, measure, &mut nodes, &mut diagnostics)?;
|
|
||||||
Ok(LaidTree { nodes, diagnostics })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Run the one solve over a built tree in `size` device px.
|
|
||||||
fn compute(built: &mut tree::Built, dev: Device, size: (f32, f32), measure: &mut dyn Measure) {
|
|
||||||
let tree::Built { taffy, root, entries, leaves, .. } = built;
|
|
||||||
let space = Size { width: AvailableSpace::Definite(size.0), height: AvailableSpace::Definite(size.1) };
|
|
||||||
// Entries come parent first, so one pass finds the deepest; the viewport and a spare few add.
|
|
||||||
let mut depth = vec![1usize; entries.len()];
|
|
||||||
for (i, entry) in entries.iter().enumerate() {
|
|
||||||
depth[i] = entry.parent.map_or(1, |parent| depth[parent] + 1);
|
|
||||||
}
|
|
||||||
let levels = depth.iter().copied().max().unwrap_or(0) + 8;
|
|
||||||
stacker::grow(STACK_PER_LEVEL * levels, || {
|
|
||||||
taffy
|
|
||||||
.compute_layout_with_measure(*root, space, |inputs, _, context, style| {
|
|
||||||
let leaf = context.and_then(|index| leaves.get(*index));
|
|
||||||
compute_leaf_layout(
|
|
||||||
inputs,
|
|
||||||
style,
|
|
||||||
|_, _| 0.0,
|
|
||||||
|known, space| match leaf {
|
|
||||||
Some(leaf) => measure::measure_leaf(measure, leaf, dev, known, space),
|
|
||||||
None => Size::ZERO,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.expect("taffy: the root is in the tree")
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Build and solve one Taffy tree in `size` device px, its origin at `origin`, and append its laid
|
|
||||||
/// nodes (absolute, in entry order) and its diagnostics. Returns the Overlays the tree met in flow.
|
|
||||||
///
|
|
||||||
/// One build, one solve: a control's form is read off the height Taffy laid it, never fed back.
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
|
||||||
fn solve<'a>(
|
|
||||||
tree: &'a BoundTree,
|
|
||||||
top: tree::Top<'a>,
|
|
||||||
dev: Device,
|
|
||||||
size: (f32, f32),
|
|
||||||
origin: (f32, f32),
|
|
||||||
measure: &mut dyn Measure,
|
|
||||||
nodes: &mut Vec<LaidNode>,
|
|
||||||
diagnostics: &mut Vec<Diagnostic>,
|
|
||||||
) -> Result<Vec<&'a OverlayNode>, LayoutError> {
|
|
||||||
let mut built = tree::build(tree, dev, top, size, measure);
|
|
||||||
compute(&mut built, dev, size, measure);
|
|
||||||
let tree::Built { taffy, entries, diagnostics: own, overlays, .. } = &mut built;
|
|
||||||
let base = nodes.len();
|
|
||||||
let mut absolute: Vec<(f32, f32)> = Vec::with_capacity(entries.len());
|
|
||||||
for entry in entries.iter() {
|
|
||||||
let laid = taffy.layout(entry.node).expect("taffy: node is in the tree");
|
|
||||||
let (px, py) = entry.parent.map_or(origin, |parent| absolute[parent]);
|
|
||||||
let (x, y) = (px + laid.location.x, py + laid.location.y);
|
|
||||||
let (w, h) = (laid.size.width, laid.size.height);
|
|
||||||
// The content row's laid height. A control without a content node (a Pixels Button, a
|
|
||||||
// non-control) passes `h`, which the form never reads.
|
|
||||||
let row = entry.control.and_then(|c| c.inner).map_or(h, |inner| taffy.layout(inner).expect("taffy: node is in the tree").size.height);
|
|
||||||
let form = dev.form(h, row);
|
|
||||||
let (ix, iy) = entry.control.filter(|c| c.inset).map_or((0.0, 0.0), |_| dev.inset(form, w, h));
|
|
||||||
// The origin the children are placed from: a control's content node sits where the inset
|
|
||||||
// says, not where Taffy put it.
|
|
||||||
absolute.push(if entry.control.is_some_and(|c| c.inner.is_some()) { (x + ix, y + iy) } else { (x, y) });
|
|
||||||
// Taffy's content extent is measured from the padding box. `content` is never smaller than
|
|
||||||
// the border box; `max_scroll` is what the content reaches past the padding box.
|
|
||||||
let reached = entry.scroll.then(|| {
|
|
||||||
let overflow = laid.scrollable_overflow_rect.rect();
|
|
||||||
let round = |v: f32| (v + 0.5).floor();
|
|
||||||
(round(overflow.right), round(overflow.bottom))
|
|
||||||
});
|
|
||||||
let content = reached.map(|(cw, ch)| (clean(cw.max(w)), clean(ch.max(h))));
|
|
||||||
let max_scroll = reached.map(|(cw, ch)| {
|
|
||||||
let inner_w = w - laid.border.left - laid.border.right;
|
|
||||||
let inner_h = h - laid.border.top - laid.border.bottom;
|
|
||||||
(clean((cw - inner_w).max(0.0)), clean((ch - inner_h).max(0.0)))
|
|
||||||
});
|
|
||||||
// Precision is a property of the whole layout: a position or an extent past the bound
|
|
||||||
// (a sum along an axis included) refuses it, so no value is silently rounded.
|
|
||||||
let reach = [x, y, x + w, y + h, content.map_or(0.0, |c| c.0), content.map_or(0.0, |c| c.1)];
|
|
||||||
if reach.iter().any(|v| !v.is_finite() || v.abs() > MAX_DEVICE) {
|
|
||||||
return Err(LayoutError::OutOfRange(Diagnostic {
|
|
||||||
code: Code::LayoutOutOfRange,
|
|
||||||
surface: tree.resolved().document().record_key(),
|
|
||||||
node: Some(entry.id.clone()),
|
|
||||||
detail: "position or extent past the precision bound".to_string(),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
let clip = entry.clip.then(|| Rect {
|
|
||||||
x: clean(x + laid.border.left),
|
|
||||||
y: clean(y + laid.border.top),
|
|
||||||
w: clean(w - laid.border.left - laid.border.right),
|
|
||||||
h: clean(h - laid.border.top - laid.border.bottom),
|
|
||||||
});
|
|
||||||
let control = entry.control.map(|_| LaidControl {
|
|
||||||
form,
|
|
||||||
content: Rect { x: clean(x + ix), y: clean(y + iy), w: clean(w - 2.0 * ix), h: clean(h - 2.0 * iy) },
|
|
||||||
});
|
|
||||||
nodes.push(LaidNode {
|
|
||||||
id: entry.id.clone(),
|
|
||||||
parent: entry.parent.map(|parent| (base + parent) as u32),
|
|
||||||
rect: Rect { x: clean(x), y: clean(y), w: clean(w), h: clean(h) },
|
|
||||||
content,
|
|
||||||
max_scroll,
|
|
||||||
clip,
|
|
||||||
control,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
diagnostics.append(own);
|
|
||||||
Ok(std::mem::take(overlays))
|
|
||||||
}
|
|
||||||
|
|
@ -1,55 +0,0 @@
|
||||||
//! The overlay pass: each Overlay is its own Taffy root, laid out against its anchor after the
|
|
||||||
//! main pass and appended after every main-tree node, which is the paint order (overlays last).
|
|
||||||
//! The viewport and a node anchor share one placement: the anchor's rect is the overlay's origin
|
|
||||||
//! and size.
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
use thing_contract::{Anchor, NodeId, OverlayNode};
|
|
||||||
|
|
||||||
use super::measure::Device;
|
|
||||||
use super::tree::Top;
|
|
||||||
use super::{LaidNode, LayoutError, Measure, Rect, solve};
|
|
||||||
use crate::bind::BoundTree;
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
|
|
||||||
/// Lay out `first` and every Overlay nested in them: each Overlay before the Overlays inside it,
|
|
||||||
/// in document order, so an anchor inside an earlier Overlay resolves. An anchor that is not laid
|
|
||||||
/// (hidden, absent) places the overlay against the viewport and is named once.
|
|
||||||
pub(super) fn place_all<'a>(
|
|
||||||
tree: &'a BoundTree,
|
|
||||||
dev: Device,
|
|
||||||
viewport: (f32, f32),
|
|
||||||
first: Vec<&'a OverlayNode>,
|
|
||||||
measure: &mut dyn Measure,
|
|
||||||
nodes: &mut Vec<LaidNode>,
|
|
||||||
diagnostics: &mut Vec<Diagnostic>,
|
|
||||||
) -> Result<(), LayoutError> {
|
|
||||||
let mut rects: HashMap<NodeId, Rect> = nodes.iter().map(|n| (n.id.clone(), n.rect)).collect();
|
|
||||||
let mut pending: Vec<&OverlayNode> = first;
|
|
||||||
pending.reverse();
|
|
||||||
while let Some(overlay) = pending.pop() {
|
|
||||||
let anchor = match &overlay.anchor {
|
|
||||||
Anchor::Viewport => Rect { x: 0.0, y: 0.0, w: viewport.0, h: viewport.1 },
|
|
||||||
Anchor::Node(anchor) => match rects.get(&anchor.node) {
|
|
||||||
Some(rect) => *rect,
|
|
||||||
None => {
|
|
||||||
diagnostics.push(Diagnostic {
|
|
||||||
code: Code::OverlayAnchorMissing,
|
|
||||||
surface: tree.resolved().document().record_key(),
|
|
||||||
node: Some(overlay.common.id.clone()),
|
|
||||||
detail: anchor.node.as_str().to_string(),
|
|
||||||
});
|
|
||||||
Rect { x: 0.0, y: 0.0, w: viewport.0, h: viewport.1 }
|
|
||||||
}
|
|
||||||
},
|
|
||||||
};
|
|
||||||
let start = nodes.len();
|
|
||||||
let nested = solve(tree, Top::Overlay(overlay), dev, (anchor.w, anchor.h), (anchor.x, anchor.y), measure, nodes, diagnostics)?;
|
|
||||||
for node in &nodes[start..] {
|
|
||||||
rects.entry(node.id.clone()).or_insert(node.rect);
|
|
||||||
}
|
|
||||||
pending.extend(nested.into_iter().rev());
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
@ -1,295 +0,0 @@
|
||||||
//! The one style map: `BoxStyle` and `Paint` onto Taffy's `Style`. The destructure names every
|
|
||||||
//! contract field, so a new field fails to compile until it is mapped.
|
|
||||||
//!
|
|
||||||
//! A slot holding a value its CSS counterpart forbids (a non-finite or oversized number, a
|
|
||||||
//! negative where none is allowed, a Dimension arm the slot cannot take) takes its initial value
|
|
||||||
//! and is reported once by field name. `Percent` is authored in percent points (50 is half).
|
|
||||||
|
|
||||||
use taffy::style_helpers::TaffyZero;
|
|
||||||
use taffy::{
|
|
||||||
AlignContent, AlignItems, Dimension, Display as TDisplay, FlexDirection, FlexWrap, GridTemplateComponent,
|
|
||||||
LengthPercentage, LengthPercentageAuto, MaxTrackSizingFunction, MinTrackSizingFunction, Overflow as TOverflow,
|
|
||||||
Point, Position as TPosition, Rect, Size, Style, TrackSizingFunction,
|
|
||||||
};
|
|
||||||
use thing_contract as c;
|
|
||||||
|
|
||||||
use super::measure::{Axis, Device, MAX_DEVICE};
|
|
||||||
|
|
||||||
/// Field names of the slots that took their initial value.
|
|
||||||
pub(super) type Invalid = Vec<&'static str>;
|
|
||||||
|
|
||||||
fn number(value: f64, negative: bool) -> Option<f32> {
|
|
||||||
let fits = value.is_finite() && value.abs() <= f64::from(MAX_DEVICE) && (negative || value >= 0.0);
|
|
||||||
fits.then_some(value as f32)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn length(scalar: &c::Scalar, dev: Device, axis: Axis, negative: bool) -> Option<f32> {
|
|
||||||
number(scalar.value, negative).map(|v| dev.length(v, axis)).filter(|v| v.abs() <= MAX_DEVICE)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn percent(scalar: &c::Scalar, negative: bool) -> Option<f32> {
|
|
||||||
number(scalar.value, negative).map(|v| v / 100.0)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn lp(d: &c::Dimension, dev: Device, axis: Axis) -> Option<LengthPercentage> {
|
|
||||||
match d {
|
|
||||||
c::Dimension::Px(s) => length(s, dev, axis, false).map(LengthPercentage::length),
|
|
||||||
c::Dimension::Percent(s) => percent(s, false).map(LengthPercentage::percent),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn lpa(d: &c::Dimension, dev: Device, axis: Axis, negative: bool) -> Option<LengthPercentageAuto> {
|
|
||||||
match d {
|
|
||||||
c::Dimension::Px(s) => length(s, dev, axis, negative).map(LengthPercentageAuto::length),
|
|
||||||
c::Dimension::Percent(s) => percent(s, negative).map(LengthPercentageAuto::percent),
|
|
||||||
c::Dimension::Auto => Some(LengthPercentageAuto::auto()),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn size_dim(d: &c::Dimension, dev: Device, axis: Axis) -> Option<Dimension> {
|
|
||||||
match d {
|
|
||||||
c::Dimension::Px(s) => length(s, dev, axis, false).map(Dimension::length),
|
|
||||||
c::Dimension::Percent(s) => percent(s, false).map(Dimension::percent),
|
|
||||||
c::Dimension::Auto => Some(Dimension::auto()),
|
|
||||||
c::Dimension::Content => Some(Dimension::fit_content()),
|
|
||||||
c::Dimension::Fr(_) => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn basis_dim(d: &c::Dimension, dev: Device, axis: Axis) -> Option<Dimension> {
|
|
||||||
match d {
|
|
||||||
c::Dimension::Content => Some(Dimension::content()),
|
|
||||||
c::Dimension::Fr(_) => None,
|
|
||||||
other => size_dim(other, dev, axis),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn track(d: &c::Dimension, dev: Device, axis: Axis) -> Option<GridTemplateComponent<String>> {
|
|
||||||
use MaxTrackSizingFunction as Max;
|
|
||||||
use MinTrackSizingFunction as Min;
|
|
||||||
let (min, max) = match d {
|
|
||||||
c::Dimension::Px(s) => {
|
|
||||||
let v = length(s, dev, axis, false)?;
|
|
||||||
(Min::length(v), Max::length(v))
|
|
||||||
}
|
|
||||||
c::Dimension::Percent(s) => {
|
|
||||||
let v = percent(s, false)?;
|
|
||||||
(Min::percent(v), Max::percent(v))
|
|
||||||
}
|
|
||||||
c::Dimension::Fr(s) => (Min::auto(), Max::fr(number(s.value, false)?)),
|
|
||||||
c::Dimension::Auto => (Min::auto(), Max::auto()),
|
|
||||||
c::Dimension::Content => (Min::max_content(), Max::max_content()),
|
|
||||||
};
|
|
||||||
Some(GridTemplateComponent::Single(TrackSizingFunction { min, max }))
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Slots {
|
|
||||||
dev: Device,
|
|
||||||
invalid: Invalid,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Slots {
|
|
||||||
fn take<T>(&mut self, field: &'static str, value: Option<T>, initial: T) -> T {
|
|
||||||
value.unwrap_or_else(|| {
|
|
||||||
if !self.invalid.contains(&field) {
|
|
||||||
self.invalid.push(field);
|
|
||||||
}
|
|
||||||
initial
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn size2(&mut self, field: &'static str, s: &c::Size2) -> Size<Dimension> {
|
|
||||||
let dev = self.dev;
|
|
||||||
Size {
|
|
||||||
width: self.take(field, size_dim(&s.width, dev, Axis::X), Dimension::auto()),
|
|
||||||
height: self.take(field, size_dim(&s.height, dev, Axis::Y), Dimension::auto()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn size2_lpa(&mut self, field: &'static str, s: &c::Size2) -> Size<LengthPercentageAuto> {
|
|
||||||
let dev = self.dev;
|
|
||||||
Size {
|
|
||||||
width: self.take(field, lpa(&s.width, dev, Axis::X, false), LengthPercentageAuto::auto()),
|
|
||||||
height: self.take(field, lpa(&s.height, dev, Axis::Y, false), LengthPercentageAuto::auto()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn edges_lpa(
|
|
||||||
&mut self,
|
|
||||||
field: &'static str,
|
|
||||||
e: &c::Edges,
|
|
||||||
negative: bool,
|
|
||||||
initial: LengthPercentageAuto,
|
|
||||||
) -> Rect<LengthPercentageAuto> {
|
|
||||||
let dev = self.dev;
|
|
||||||
Rect {
|
|
||||||
left: self.take(field, lpa(&e.left, dev, Axis::X, negative), initial),
|
|
||||||
right: self.take(field, lpa(&e.right, dev, Axis::X, negative), initial),
|
|
||||||
top: self.take(field, lpa(&e.top, dev, Axis::Y, negative), initial),
|
|
||||||
bottom: self.take(field, lpa(&e.bottom, dev, Axis::Y, negative), initial),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn edges_lp(&mut self, field: &'static str, e: &c::Edges) -> Rect<LengthPercentage> {
|
|
||||||
let dev = self.dev;
|
|
||||||
let zero = LengthPercentage::ZERO;
|
|
||||||
Rect {
|
|
||||||
left: self.take(field, lp(&e.left, dev, Axis::X), zero),
|
|
||||||
right: self.take(field, lp(&e.right, dev, Axis::X), zero),
|
|
||||||
top: self.take(field, lp(&e.top, dev, Axis::Y), zero),
|
|
||||||
bottom: self.take(field, lp(&e.bottom, dev, Axis::Y), zero),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn tracks(&mut self, field: &'static str, axis: Axis, dims: &[c::Dimension]) -> Vec<GridTemplateComponent<String>> {
|
|
||||||
let dev = self.dev;
|
|
||||||
let tracks: Option<Vec<_>> = dims.iter().map(|d| track(d, dev, axis)).collect();
|
|
||||||
self.take(field, tracks, Vec::new())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn weight(&mut self, field: &'static str, value: f64, initial: f32) -> f32 {
|
|
||||||
self.take(field, number(value, false), initial)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn item(align: &c::ItemAlign) -> Option<AlignItems> {
|
|
||||||
Some(match align {
|
|
||||||
c::ItemAlign::Auto => return None,
|
|
||||||
c::ItemAlign::Start => AlignItems::FLEX_START,
|
|
||||||
c::ItemAlign::End => AlignItems::FLEX_END,
|
|
||||||
c::ItemAlign::Center => AlignItems::CENTER,
|
|
||||||
c::ItemAlign::Stretch => AlignItems::STRETCH,
|
|
||||||
c::ItemAlign::Baseline => AlignItems::BASELINE,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn content(align: &c::ContentAlign, auto: AlignContent) -> AlignContent {
|
|
||||||
match align {
|
|
||||||
c::ContentAlign::Auto => auto,
|
|
||||||
c::ContentAlign::Start => AlignContent::FLEX_START,
|
|
||||||
c::ContentAlign::End => AlignContent::FLEX_END,
|
|
||||||
c::ContentAlign::Center => AlignContent::CENTER,
|
|
||||||
c::ContentAlign::Stretch => AlignContent::STRETCH,
|
|
||||||
c::ContentAlign::SpaceBetween => AlignContent::SPACE_BETWEEN,
|
|
||||||
c::ContentAlign::SpaceAround => AlignContent::SPACE_AROUND,
|
|
||||||
c::ContentAlign::SpaceEvenly => AlignContent::SPACE_EVENLY,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The Taffy style of a Box. `dev` converts Px lengths to the solver's device units; the slots that were not legal are named in the second value.
|
|
||||||
/// `main` is the main axis of the flex container this box is a child of: a flex basis runs along
|
|
||||||
/// its parent's main axis, not the box's own.
|
|
||||||
pub(super) fn box_style(s: &c::BoxStyle, paint: &c::Paint, dev: Device, main: Axis) -> (Style, Invalid) {
|
|
||||||
let c::BoxStyle {
|
|
||||||
display,
|
|
||||||
direction,
|
|
||||||
wrap,
|
|
||||||
gap,
|
|
||||||
padding,
|
|
||||||
margin,
|
|
||||||
size,
|
|
||||||
min_size,
|
|
||||||
max_size,
|
|
||||||
position,
|
|
||||||
inset,
|
|
||||||
overflow,
|
|
||||||
align_items,
|
|
||||||
align_self,
|
|
||||||
align_content,
|
|
||||||
justify_content,
|
|
||||||
grow,
|
|
||||||
shrink,
|
|
||||||
basis,
|
|
||||||
grid_columns,
|
|
||||||
grid_rows,
|
|
||||||
} = s;
|
|
||||||
let mut slots = Slots { dev, invalid: Vec::new() };
|
|
||||||
// A border is one width on four sides: across (left, right) and down (top, bottom) it
|
|
||||||
// converts at its own axis.
|
|
||||||
let (border_x, border_y) = match &paint.border {
|
|
||||||
None => (LengthPercentage::ZERO, LengthPercentage::ZERO),
|
|
||||||
Some(b) => {
|
|
||||||
let side = |axis| number(b.width, false).map(|v| dev.border(v, axis)).filter(|v| v.abs() <= MAX_DEVICE);
|
|
||||||
let across = slots.take("border", side(Axis::X), 0.0);
|
|
||||||
let down = side(Axis::Y).unwrap_or(0.0);
|
|
||||||
(LengthPercentage::length(across), LengthPercentage::length(down))
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let overflow = match overflow {
|
|
||||||
c::Overflow::Visible => TOverflow::Visible,
|
|
||||||
c::Overflow::Clip => TOverflow::Clip,
|
|
||||||
c::Overflow::Scroll => TOverflow::Scroll,
|
|
||||||
};
|
|
||||||
let gap = {
|
|
||||||
let width = slots.take("gap", lp(&gap.width, dev, Axis::X), LengthPercentage::ZERO);
|
|
||||||
let height = slots.take("gap", lp(&gap.height, dev, Axis::Y), LengthPercentage::ZERO);
|
|
||||||
Size { width, height }
|
|
||||||
};
|
|
||||||
let style = Style {
|
|
||||||
display: match display {
|
|
||||||
c::Display::Flex => TDisplay::Flex,
|
|
||||||
c::Display::Grid => TDisplay::Grid,
|
|
||||||
c::Display::Block => TDisplay::Block,
|
|
||||||
},
|
|
||||||
flex_direction: match direction {
|
|
||||||
c::Direction::Row => FlexDirection::Row,
|
|
||||||
c::Direction::Column => FlexDirection::Column,
|
|
||||||
c::Direction::RowReverse => FlexDirection::RowReverse,
|
|
||||||
c::Direction::ColumnReverse => FlexDirection::ColumnReverse,
|
|
||||||
},
|
|
||||||
flex_wrap: match wrap {
|
|
||||||
c::Wrap::NoWrap => FlexWrap::NoWrap,
|
|
||||||
c::Wrap::Wrap => FlexWrap::Wrap,
|
|
||||||
c::Wrap::WrapReverse => FlexWrap::WrapReverse,
|
|
||||||
},
|
|
||||||
gap,
|
|
||||||
padding: slots.edges_lp("padding", padding),
|
|
||||||
border: Rect { left: border_x, right: border_x, top: border_y, bottom: border_y },
|
|
||||||
margin: slots.edges_lpa("margin", margin, true, LengthPercentageAuto::ZERO),
|
|
||||||
size: slots.size2("size", size),
|
|
||||||
min_size: slots.size2_lpa("min_size", min_size),
|
|
||||||
max_size: slots.size2_lpa("max_size", max_size),
|
|
||||||
position: match position {
|
|
||||||
c::Position::Relative => TPosition::Relative,
|
|
||||||
c::Position::Absolute => TPosition::Absolute,
|
|
||||||
},
|
|
||||||
inset: slots.edges_lpa("inset", inset, true, LengthPercentageAuto::auto()),
|
|
||||||
overflow: Point { x: overflow, y: overflow },
|
|
||||||
scrollbar_width: 0.0,
|
|
||||||
align_items: item(align_items).unwrap_or(AlignItems::STRETCH),
|
|
||||||
align_self: item(align_self),
|
|
||||||
align_content: content(align_content, AlignContent::STRETCH),
|
|
||||||
justify_content: content(justify_content, AlignContent::FLEX_START),
|
|
||||||
flex_grow: slots.weight("grow", *grow, 0.0),
|
|
||||||
flex_shrink: slots.weight("shrink", *shrink, 1.0),
|
|
||||||
flex_basis: {
|
|
||||||
let basis = basis_dim(basis, dev, main);
|
|
||||||
slots.take("basis", basis, Dimension::auto())
|
|
||||||
},
|
|
||||||
grid_template_columns: slots.tracks("grid_columns", Axis::X, grid_columns).into_iter().collect(),
|
|
||||||
grid_template_rows: slots.tracks("grid_rows", Axis::Y, grid_rows).into_iter().collect(),
|
|
||||||
..Style::default()
|
|
||||||
};
|
|
||||||
(style, slots.invalid)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An Embed's style: exactly its declared size, never shrunk.
|
|
||||||
pub(super) fn embed_style(width: f64, height: f64, dev: Device) -> (Style, Invalid) {
|
|
||||||
let mut slots = Slots { dev, invalid: Vec::new() };
|
|
||||||
let side = |slots: &mut Slots, value: f64, axis: Axis| {
|
|
||||||
let v = slots.take("size", length(&c::Scalar { value }, dev, axis, false), 0.0);
|
|
||||||
(Dimension::length(v), LengthPercentageAuto::length(v))
|
|
||||||
};
|
|
||||||
let (w, wa) = side(&mut slots, width, Axis::X);
|
|
||||||
let (h, ha) = side(&mut slots, height, Axis::Y);
|
|
||||||
let style = Style {
|
|
||||||
size: Size { width: w, height: h },
|
|
||||||
min_size: Size { width: wa, height: ha },
|
|
||||||
max_size: Size { width: wa, height: ha },
|
|
||||||
flex_shrink: 0.0,
|
|
||||||
..Style::default()
|
|
||||||
};
|
|
||||||
(style, slots.invalid)
|
|
||||||
}
|
|
||||||
|
|
@ -1,389 +0,0 @@
|
||||||
//! The walk: a `BoundTree` becomes a Taffy tree, one Taffy node per laid node, Repeats spliced.
|
|
||||||
|
|
||||||
use taffy::{Style, TaffyTree};
|
|
||||||
use thing_contract::{Direction, Node, NodeId, Overflow, OverlayNode};
|
|
||||||
|
|
||||||
use super::ControlForm;
|
|
||||||
use super::measure::{Axis, Device, Leaf, MAX_DEVICE, intrinsic_ratio};
|
|
||||||
use super::style::{Invalid, box_style, embed_style};
|
|
||||||
use crate::bind::{Bound, BoundTree, Field};
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
use crate::resolve::grow;
|
|
||||||
|
|
||||||
static ABSENT: Bound = Bound::Absent;
|
|
||||||
|
|
||||||
/// One laid node, in document order. `parent` is the entry of the nearest laid ancestor.
|
|
||||||
pub(super) struct Entry<'a> {
|
|
||||||
pub(super) id: &'a NodeId,
|
|
||||||
pub(super) node: taffy::NodeId,
|
|
||||||
pub(super) parent: Option<usize>,
|
|
||||||
pub(super) clip: bool,
|
|
||||||
pub(super) scroll: bool,
|
|
||||||
/// A control (Button, TextInput, Select, Toggle): its form and content box are published.
|
|
||||||
pub(super) control: Option<Control>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What `solve` needs to state a control: whether layout reserves it an inset (every control but a
|
|
||||||
/// Pixels Button) and, in Cells, the content node inside its shell whose children are placed from
|
|
||||||
/// the inset origin.
|
|
||||||
#[derive(Clone, Copy)]
|
|
||||||
pub(super) struct Control {
|
|
||||||
pub(super) inner: Option<taffy::NodeId>,
|
|
||||||
pub(super) inset: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) struct Built<'a> {
|
|
||||||
pub(super) taffy: TaffyTree<usize>,
|
|
||||||
pub(super) root: taffy::NodeId,
|
|
||||||
pub(super) entries: Vec<Entry<'a>>,
|
|
||||||
/// The Taffy context of a measured leaf is its index here.
|
|
||||||
pub(super) leaves: Vec<Leaf<'a>>,
|
|
||||||
pub(super) diagnostics: Vec<Diagnostic>,
|
|
||||||
/// The visible Overlays met in flow, in document order, for the overlay pass.
|
|
||||||
pub(super) overlays: Vec<&'a OverlayNode>,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Builder<'a, 'm> {
|
|
||||||
tree: &'a BoundTree,
|
|
||||||
surface: String,
|
|
||||||
dev: Device,
|
|
||||||
measure: &'m mut dyn super::Measure,
|
|
||||||
taffy: TaffyTree<usize>,
|
|
||||||
entries: Vec<Entry<'a>>,
|
|
||||||
leaves: Vec<Leaf<'a>>,
|
|
||||||
diagnostics: Vec<Diagnostic>,
|
|
||||||
overlays: Vec<&'a OverlayNode>,
|
|
||||||
/// The main axis of the container whose children are being visited: the axis a child's flex
|
|
||||||
/// basis runs along. The viewport is a block, whose children take no basis; across stands.
|
|
||||||
main: Axis,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What the Taffy tree is rooted at: the viewport holding the document root, or one Overlay.
|
|
||||||
#[derive(Clone, Copy)]
|
|
||||||
pub(super) enum Top<'a> {
|
|
||||||
Document,
|
|
||||||
Overlay(&'a OverlayNode),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Build one Taffy tree of `size` device px. The document's tree is a block container (the
|
|
||||||
/// viewport) the root flows in, so a root with an auto width fills it and a Repeat at the root has
|
|
||||||
/// a parent to splice into. An Overlay's tree is the Overlay itself, the first entry: a container
|
|
||||||
/// of Taffy's default style the anchor's size, so its children are laid against the anchor.
|
|
||||||
pub(super) fn build<'a>(
|
|
||||||
tree: &'a BoundTree,
|
|
||||||
dev: Device,
|
|
||||||
top: Top<'a>,
|
|
||||||
size: (f32, f32),
|
|
||||||
measure: &mut dyn super::Measure,
|
|
||||||
) -> Built<'a> {
|
|
||||||
let document = tree.resolved().document();
|
|
||||||
let mut builder = Builder {
|
|
||||||
tree,
|
|
||||||
surface: document.record_key(),
|
|
||||||
dev,
|
|
||||||
measure,
|
|
||||||
taffy: TaffyTree::new(),
|
|
||||||
entries: Vec::new(),
|
|
||||||
leaves: Vec::new(),
|
|
||||||
diagnostics: Vec::new(),
|
|
||||||
overlays: Vec::new(),
|
|
||||||
main: Axis::X,
|
|
||||||
};
|
|
||||||
let mut kids = Vec::new();
|
|
||||||
let mut style = Style {
|
|
||||||
size: taffy::Size { width: taffy::Dimension::length(size.0), height: taffy::Dimension::length(size.1) },
|
|
||||||
..Style::default()
|
|
||||||
};
|
|
||||||
let overlay = match top {
|
|
||||||
Top::Document => {
|
|
||||||
builder.visit(&document.root, None, &mut kids);
|
|
||||||
style.display = taffy::Display::Block;
|
|
||||||
style.position = taffy::Position::Relative;
|
|
||||||
None
|
|
||||||
}
|
|
||||||
Top::Overlay(overlay) => {
|
|
||||||
let index = builder.entry(&overlay.common.id, None, &Overflow::Visible);
|
|
||||||
for child in &overlay.children {
|
|
||||||
builder.visit(child, Some(index), &mut kids);
|
|
||||||
}
|
|
||||||
Some(index)
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let root = builder.taffy.new_with_children(style, &kids).expect("taffy: insert");
|
|
||||||
if let Some(index) = overlay {
|
|
||||||
builder.entries[index].node = root;
|
|
||||||
}
|
|
||||||
Built {
|
|
||||||
taffy: builder.taffy,
|
|
||||||
root,
|
|
||||||
entries: builder.entries,
|
|
||||||
leaves: builder.leaves,
|
|
||||||
diagnostics: builder.diagnostics,
|
|
||||||
overlays: builder.overlays,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> Builder<'a, '_> {
|
|
||||||
/// The shell of a Cells control: a grid of three rows (an edge row of up to one row above and
|
|
||||||
/// below, the content row between) one cell in on each side, the inset rule's numbers
|
|
||||||
/// (`Device::inset`). The content node takes the middle row, at least its children's height of it (one row if it has none). The edge
|
|
||||||
/// rows give way first, so the shell lays anywhere from one row up and the form is read off the
|
|
||||||
/// height it ends with (`Device::form`).
|
|
||||||
fn shell(&mut self, content: taffy::NodeId) -> taffy::NodeId {
|
|
||||||
use taffy::style_helpers::{auto, length, line, minmax};
|
|
||||||
let (across, down) = self.dev.inset(ControlForm::Bordered, f32::INFINITY, f32::INFINITY);
|
|
||||||
let mut seat = self.taffy.style(content).expect("taffy: node is in the tree").clone();
|
|
||||||
// A content node with children is never laid shorter than they are (its automatic minimum),
|
|
||||||
// so the row the form reads is the content's own height; a leaf or an empty Button holds one row.
|
|
||||||
if self.taffy.children(content).expect("taffy: node is in the tree").is_empty() {
|
|
||||||
seat.min_size.height = taffy::LengthPercentageAuto::length(1.0);
|
|
||||||
}
|
|
||||||
seat.grid_row = taffy::Line { start: line(2), end: auto() };
|
|
||||||
self.taffy.set_style(content, seat).expect("taffy: style");
|
|
||||||
let edge = || -> taffy::GridTemplateComponent<String> { minmax::<taffy::TrackSizingFunction>(length(0.0), length(down)).into() };
|
|
||||||
let content_row: taffy::GridTemplateComponent<String> = minmax::<taffy::TrackSizingFunction>(auto(), auto()).into();
|
|
||||||
let style = Style {
|
|
||||||
display: taffy::Display::Grid,
|
|
||||||
grid_template_rows: vec![edge(), content_row, edge()],
|
|
||||||
padding: taffy::Rect {
|
|
||||||
left: taffy::LengthPercentage::length(across),
|
|
||||||
right: taffy::LengthPercentage::length(across),
|
|
||||||
top: taffy::LengthPercentage::length(0.0),
|
|
||||||
bottom: taffy::LengthPercentage::length(0.0),
|
|
||||||
},
|
|
||||||
..Style::default()
|
|
||||||
};
|
|
||||||
self.taffy.new_with_children(style, &[content]).expect("taffy: insert")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn hidden(&self, id: &NodeId) -> bool {
|
|
||||||
matches!(self.tree.value(id, Field::Visible), Some(Bound::Bool(false)))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn value(&self, id: &NodeId, field: Field) -> &'a Bound {
|
|
||||||
self.tree.value(id, field).unwrap_or(&ABSENT)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn report(&mut self, id: &NodeId, invalid: Invalid) {
|
|
||||||
for field in invalid {
|
|
||||||
self.diagnostics.push(Diagnostic {
|
|
||||||
code: Code::StyleValueInvalid,
|
|
||||||
surface: self.surface.clone(),
|
|
||||||
node: Some(id.clone()),
|
|
||||||
detail: field.to_string(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn entry(&mut self, id: &'a NodeId, parent: Option<usize>, overflow: &Overflow) -> usize {
|
|
||||||
let clip = !matches!(overflow, Overflow::Visible);
|
|
||||||
let scroll = matches!(overflow, Overflow::Scroll);
|
|
||||||
self.entries.push(Entry { id, node: taffy::NodeId::from(0u64), parent, clip, scroll, control: None });
|
|
||||||
self.entries.len() - 1
|
|
||||||
}
|
|
||||||
|
|
||||||
fn leaf(&mut self, id: &'a NodeId, parent: Option<usize>, leaf: Leaf<'a>, out: &mut Vec<taffy::NodeId>) {
|
|
||||||
let mut style = Style::default();
|
|
||||||
if matches!(leaf, Leaf::Image { .. }) {
|
|
||||||
// A stretched image keeps its shape: the ratio is what the measure says it is unconstrained.
|
|
||||||
// Whatever its ratio derives, a side of the image stays within the length bound.
|
|
||||||
let bound = taffy::LengthPercentageAuto::length(MAX_DEVICE);
|
|
||||||
style.max_size = taffy::Size { width: bound, height: bound };
|
|
||||||
// An invalid measure leaves the image unconstrained (no ratio, not replaced) and is named.
|
|
||||||
match intrinsic_ratio(self.measure, &leaf, self.dev) {
|
|
||||||
Ok(ratio) => {
|
|
||||||
style.item_is_replaced = true;
|
|
||||||
style.aspect_ratio = ratio;
|
|
||||||
}
|
|
||||||
Err(()) => self.report(id, vec!["measure"]),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let control = matches!(leaf, Leaf::TextInput { .. } | Leaf::Toggle { .. } | Leaf::Select { .. });
|
|
||||||
let index = self.entry(id, parent, &Overflow::Visible);
|
|
||||||
let context = self.leaves.len();
|
|
||||||
self.leaves.push(leaf);
|
|
||||||
let mut node = self.taffy.new_leaf_with_context(style, context).expect("taffy: insert");
|
|
||||||
if control {
|
|
||||||
// In Cells the leaf sits in its shell, which is the control's laid node.
|
|
||||||
let inner = self.dev.cells().then_some(node);
|
|
||||||
if inner.is_some() {
|
|
||||||
node = self.shell(node);
|
|
||||||
}
|
|
||||||
self.entries[index].control = Some(Control { inner, inset: true });
|
|
||||||
}
|
|
||||||
self.entries[index].node = node;
|
|
||||||
out.push(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn container(
|
|
||||||
&mut self,
|
|
||||||
id: &'a NodeId,
|
|
||||||
parent: Option<usize>,
|
|
||||||
style: (Style, Invalid),
|
|
||||||
overflow: &Overflow,
|
|
||||||
main: Axis,
|
|
||||||
children: &'a [Node],
|
|
||||||
out: &mut Vec<taffy::NodeId>,
|
|
||||||
) {
|
|
||||||
let (index, node) = self.contain(id, parent, style, overflow, main, children);
|
|
||||||
self.entries[index].node = node;
|
|
||||||
out.push(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The entry and Taffy node of a container, its children visited; the caller seats the node.
|
|
||||||
fn contain(
|
|
||||||
&mut self,
|
|
||||||
id: &'a NodeId,
|
|
||||||
parent: Option<usize>,
|
|
||||||
(style, invalid): (Style, Invalid),
|
|
||||||
overflow: &Overflow,
|
|
||||||
main: Axis,
|
|
||||||
children: &'a [Node],
|
|
||||||
) -> (usize, taffy::NodeId) {
|
|
||||||
self.report(id, invalid);
|
|
||||||
let index = self.entry(id, parent, overflow);
|
|
||||||
let mut kids = Vec::new();
|
|
||||||
let outer = std::mem::replace(&mut self.main, main);
|
|
||||||
for child in children {
|
|
||||||
self.visit(child, Some(index), &mut kids);
|
|
||||||
}
|
|
||||||
self.main = outer;
|
|
||||||
(index, self.taffy.new_with_children(style, &kids).expect("taffy: insert"))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Append the Taffy nodes `node` contributes to its parent's children: one, none (hidden,
|
|
||||||
/// Overlay, a Repeat with no instances) or one per Repeat instance.
|
|
||||||
fn visit(&mut self, node: &'a Node, parent: Option<usize>, out: &mut Vec<taffy::NodeId>) {
|
|
||||||
grow(|| match node {
|
|
||||||
Node::Box(b) => {
|
|
||||||
if !self.hidden(&b.common.id) {
|
|
||||||
let style = box_style(&b.style, &b.paint, self.dev, self.main);
|
|
||||||
let main = match b.style.direction {
|
|
||||||
Direction::Row | Direction::RowReverse => Axis::X,
|
|
||||||
Direction::Column | Direction::ColumnReverse => Axis::Y,
|
|
||||||
};
|
|
||||||
self.container(&b.common.id, parent, style, &b.style.overflow, main, &b.children, out);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Node::Button(b) => {
|
|
||||||
if !self.hidden(&b.common.id) {
|
|
||||||
// In Cells the Button is a shell (`Builder::shell`) around a row of its content, the
|
|
||||||
// items centred in it, so a content-sized Button's box includes its border rows and
|
|
||||||
// a short one squeezes to one compact row. Pixels: render draws the chrome behind
|
|
||||||
// the content and no inset applies.
|
|
||||||
if self.dev.cells() {
|
|
||||||
let row = Style { align_items: taffy::AlignItems::CENTER, ..Style::default() };
|
|
||||||
let (index, inner) = self.contain(&b.common.id, parent, (row, Vec::new()), &Overflow::Visible, Axis::X, &b.content);
|
|
||||||
let shell = self.shell(inner);
|
|
||||||
self.entries[index].node = shell;
|
|
||||||
self.entries[index].control = Some(Control { inner: Some(inner), inset: true });
|
|
||||||
out.push(shell);
|
|
||||||
} else {
|
|
||||||
let index = self.entries.len();
|
|
||||||
self.container(&b.common.id, parent, (Style::default(), Vec::new()), &Overflow::Visible, Axis::X, &b.content, out);
|
|
||||||
self.entries[index].control = Some(Control { inner: None, inset: false });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// A Repeat has no box: its instances are its parent's children, in instance order.
|
|
||||||
Node::Repeat(r) => {
|
|
||||||
if !self.hidden(&r.common.id) {
|
|
||||||
for instance in self.tree.instances(&r.common.id) {
|
|
||||||
self.visit(&instance.root, parent, out);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// An Overlay is out of flow: nothing here; the overlay pass lays it out against its anchor.
|
|
||||||
Node::Overlay(o) => {
|
|
||||||
if !self.hidden(&o.common.id) {
|
|
||||||
self.overlays.push(o);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// A Use that stayed is resolve's placeholder (beside its diagnostic): a childless leaf
|
|
||||||
// that keeps its place so render can draw the error. A Slot never survives resolve.
|
|
||||||
Node::Use(u) => {
|
|
||||||
if !self.hidden(&u.common.id) {
|
|
||||||
let index = self.entry(&u.common.id, parent, &Overflow::Visible);
|
|
||||||
let (width, height) = self.dev.placeholder();
|
|
||||||
let least = taffy::Size { width: taffy::LengthPercentageAuto::length(width), height: taffy::LengthPercentageAuto::length(height) };
|
|
||||||
let style = Style { min_size: least, ..Style::default() };
|
|
||||||
let id = self.taffy.new_leaf(style).expect("taffy: insert");
|
|
||||||
self.entries[index].node = id;
|
|
||||||
out.push(id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Node::Slot(_) => debug_assert!(false, "resolve expands Slot"),
|
|
||||||
Node::Embed(e) => {
|
|
||||||
if !self.hidden(&e.common.id) {
|
|
||||||
let (style, invalid) = embed_style(e.width, e.height, self.dev);
|
|
||||||
self.report(&e.common.id, invalid);
|
|
||||||
let index = self.entry(&e.common.id, parent, &Overflow::Visible);
|
|
||||||
let id = self.taffy.new_leaf(style).expect("taffy: insert");
|
|
||||||
self.entries[index].node = id;
|
|
||||||
out.push(id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Node::Text(n) => {
|
|
||||||
let id = &n.common.id;
|
|
||||||
if !self.hidden(id) {
|
|
||||||
let leaf = Leaf::Text {
|
|
||||||
node: id,
|
|
||||||
content: self.value(id, Field::Content),
|
|
||||||
style_token: &n.style_token,
|
|
||||||
wrap: n.wrap,
|
|
||||||
max_lines: n.max_lines.map(|lines| lines.get().max(0) as u32),
|
|
||||||
};
|
|
||||||
self.leaf(id, parent, leaf, out);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Node::TextInput(n) => {
|
|
||||||
let id = &n.common.id;
|
|
||||||
if !self.hidden(id) {
|
|
||||||
let leaf = Leaf::TextInput {
|
|
||||||
node: id,
|
|
||||||
multiline: n.multiline,
|
|
||||||
placeholder: self.value(id, Field::Placeholder),
|
|
||||||
value: self.value(id, Field::Initial),
|
|
||||||
};
|
|
||||||
self.leaf(id, parent, leaf, out);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Node::Toggle(n) => {
|
|
||||||
if !self.hidden(&n.common.id) {
|
|
||||||
self.leaf(&n.common.id, parent, Leaf::Toggle { node: &n.common.id }, out);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Node::Slider(n) => {
|
|
||||||
if !self.hidden(&n.common.id) {
|
|
||||||
self.leaf(&n.common.id, parent, Leaf::Slider { node: &n.common.id }, out);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Node::Select(n) => {
|
|
||||||
let id = &n.common.id;
|
|
||||||
if !self.hidden(id) {
|
|
||||||
self.leaf(id, parent, Leaf::Select { node: id, selected: self.value(id, Field::Selected) }, out);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Node::Image(n) => {
|
|
||||||
if !self.hidden(&n.common.id) {
|
|
||||||
let leaf = Leaf::Image { node: &n.common.id, asset: self.value(&n.common.id, Field::Asset) };
|
|
||||||
self.leaf(&n.common.id, parent, leaf, out);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Node::Plot(n) => {
|
|
||||||
if !self.hidden(&n.common.id) {
|
|
||||||
// A plot declares no size: layout gives it the default object size.
|
|
||||||
let (width, height) = self.dev.plot();
|
|
||||||
let style = Style {
|
|
||||||
size: taffy::Size { width: taffy::Dimension::length(width), height: taffy::Dimension::length(height) },
|
|
||||||
..Style::default()
|
|
||||||
};
|
|
||||||
let index = self.entry(&n.common.id, parent, &Overflow::Visible);
|
|
||||||
let id = self.taffy.new_leaf(style).expect("taffy: insert");
|
|
||||||
self.entries[index].node = id;
|
|
||||||
out.push(id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,17 +0,0 @@
|
||||||
//! Thing's core: a function of documents, state, input and time. It touches the world only
|
|
||||||
//! through ports; it reads no clock, spawns nothing and awaits nothing.
|
|
||||||
|
|
||||||
pub mod bind;
|
|
||||||
pub mod command;
|
|
||||||
pub mod diagnostic;
|
|
||||||
pub mod frame;
|
|
||||||
pub mod input;
|
|
||||||
pub mod layout;
|
|
||||||
pub mod port;
|
|
||||||
pub mod render;
|
|
||||||
pub mod resolve;
|
|
||||||
pub mod text;
|
|
||||||
pub mod theme;
|
|
||||||
pub mod time;
|
|
||||||
|
|
||||||
pub use frame::{Config, Core, FrameInput, FrameOutput, Ports};
|
|
||||||
|
|
@ -1,53 +0,0 @@
|
||||||
//! The one interest ledger: core holds a state interest once however many readers ask for it. A
|
|
||||||
//! reader (the Resolver or the Binder) holds and releases through the ledger, never through the
|
|
||||||
//! port, so one `SubscriptionId` per interest is shared by count and an interest nothing reads
|
|
||||||
//! is unsubscribed.
|
|
||||||
|
|
||||||
use std::collections::{HashMap, HashSet};
|
|
||||||
|
|
||||||
use super::{Interest, StatePort, SubscriptionId};
|
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
|
||||||
pub struct Ledger {
|
|
||||||
held: HashMap<Interest, (SubscriptionId, usize)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Ledger {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self::default()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One more reader of `interest`; the port is asked only for the first.
|
|
||||||
pub fn hold(&mut self, port: &mut dyn StatePort, interest: &Interest) -> SubscriptionId {
|
|
||||||
let (id, count) = self.held.entry(interest.clone()).or_insert_with(|| (port.subscribe(interest.clone()), 0));
|
|
||||||
*count += 1;
|
|
||||||
*id
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One reader fewer; the port is told when the last goes. Releasing what is not held does nothing.
|
|
||||||
pub fn release(&mut self, port: &mut dyn StatePort, interest: &Interest) {
|
|
||||||
let Some((id, count)) = self.held.get_mut(interest) else { return };
|
|
||||||
*count -= 1;
|
|
||||||
if *count == 0 {
|
|
||||||
let id = *id;
|
|
||||||
self.held.remove(interest);
|
|
||||||
port.unsubscribe(id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Move one reader from the interests it held to the ones it holds now: hold only the added,
|
|
||||||
/// release only the removed, touch nothing else.
|
|
||||||
pub fn diff(&mut self, port: &mut dyn StatePort, old: &HashSet<Interest>, new: &HashSet<Interest>) {
|
|
||||||
for added in new.difference(old) {
|
|
||||||
self.hold(port, added);
|
|
||||||
}
|
|
||||||
for removed in old.difference(new) {
|
|
||||||
self.release(port, removed);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How many readers hold `interest`.
|
|
||||||
pub fn readers(&self, interest: &Interest) -> usize {
|
|
||||||
self.held.get(interest).map_or(0, |(_, count)| *count)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,154 +0,0 @@
|
||||||
//! What core may ask of state. The port reads and queues changes; nothing in it writes, and
|
|
||||||
//! it never awaits: core drains queued changes inside its frame.
|
|
||||||
|
|
||||||
pub mod ledger;
|
|
||||||
pub mod state;
|
|
||||||
|
|
||||||
pub use ledger::Ledger;
|
|
||||||
pub use state::StateValue;
|
|
||||||
|
|
||||||
use thing_contract::{AssetCatalog, CommandResult, CompositionDocument, ProviderId, RecordKey, SchemaId, SurfaceDocument};
|
|
||||||
|
|
||||||
/// One record: the provider that holds it, its schema and its key.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
|
||||||
pub struct Address {
|
|
||||||
pub provider: ProviderId,
|
|
||||||
pub schema: SchemaId,
|
|
||||||
pub key: RecordKey,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every record of one provider and schema whose key starts with `key_prefix`.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
|
||||||
pub struct Prefix {
|
|
||||||
pub provider: ProviderId,
|
|
||||||
pub schema: SchemaId,
|
|
||||||
pub key_prefix: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
|
||||||
pub enum Interest {
|
|
||||||
Record(Address),
|
|
||||||
Prefix(Prefix),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Prefix {
|
|
||||||
pub fn matches(&self, address: &Address) -> bool {
|
|
||||||
self.provider == address.provider
|
|
||||||
&& self.schema == address.schema
|
|
||||||
&& address.key.as_str().starts_with(&self.key_prefix)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Interest {
|
|
||||||
/// Whether a change at `address` is of interest.
|
|
||||||
pub fn matches(&self, address: &Address) -> bool {
|
|
||||||
match self {
|
|
||||||
Interest::Record(record) => record == address,
|
|
||||||
Interest::Prefix(prefix) => prefix.matches(address),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
|
||||||
pub struct SubscriptionId(pub u64);
|
|
||||||
|
|
||||||
/// A record the port carries, decoded: a contract kind, or a provider's state by its schema's
|
|
||||||
/// member names. `State::schema` is the schema the record is stored under, which is not the
|
|
||||||
/// one asked for when the key holds a record of another.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub enum Record {
|
|
||||||
Surface(SurfaceDocument),
|
|
||||||
Composition(CompositionDocument),
|
|
||||||
Result(CommandResult),
|
|
||||||
Catalog(AssetCatalog),
|
|
||||||
State { schema: SchemaId, value: StateValue },
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct Entry {
|
|
||||||
pub address: Address,
|
|
||||||
pub record: Record,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A record the contract refused. `detail` is the decoder's message, which never carries a
|
|
||||||
/// value.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub struct Refusal {
|
|
||||||
pub address: Address,
|
|
||||||
pub kind: SchemaId,
|
|
||||||
pub detail: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The answer for one address. A refusal is never absence.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub enum Lookup {
|
|
||||||
Present(Entry),
|
|
||||||
Absent,
|
|
||||||
Refused(Refusal),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub enum Change {
|
|
||||||
Upsert(Entry),
|
|
||||||
Delete(Address),
|
|
||||||
Refused(Refusal),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Core's view of state. Object safe, and no method writes.
|
|
||||||
pub trait StatePort {
|
|
||||||
fn read(&self, address: &Address) -> Lookup;
|
|
||||||
|
|
||||||
/// One lookup per record under the prefix, in key order, refusals included. Every lookup is of
|
|
||||||
/// the prefix's one provider and schema: a record of another schema is never listed (the
|
|
||||||
/// `Binder` relies on this; its own other-schema refusal is only a guard).
|
|
||||||
fn list(&self, prefix: &Prefix) -> Vec<Lookup>;
|
|
||||||
|
|
||||||
fn subscribe(&mut self, interest: Interest) -> SubscriptionId;
|
|
||||||
|
|
||||||
fn unsubscribe(&mut self, id: SubscriptionId);
|
|
||||||
|
|
||||||
/// Every change since the last drain that some interest matched when it happened, in mutation
|
|
||||||
/// order (unsubscribing does not recall changes already queued),
|
|
||||||
/// each once.
|
|
||||||
fn drain(&mut self) -> Vec<Change>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where core gets the 16 random bytes of an invocation id. Core sets the UUID version and
|
|
||||||
/// variant bits itself, so a source need only be unpredictable; a test source is a script or a counter.
|
|
||||||
pub trait IdSource {
|
|
||||||
fn fill(&mut self, bytes: &mut [u8; 16]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn address(provider: &str, schema: &str, key: &str) -> Address {
|
|
||||||
Address { provider: ProviderId::new(provider), schema: SchemaId::new(schema), key: RecordKey::new(key) }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn prefix(provider: &str, schema: &str, key_prefix: &str) -> Prefix {
|
|
||||||
Prefix { provider: ProviderId::new(provider), schema: SchemaId::new(schema), key_prefix: key_prefix.into() }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_prefix_matches_provider_schema_and_key_prefix_together() {
|
|
||||||
let under = prefix("p", "s", "row-");
|
|
||||||
assert!(under.matches(&address("p", "s", "row-1")));
|
|
||||||
assert!(under.matches(&address("p", "s", "row-")));
|
|
||||||
assert!(!under.matches(&address("q", "s", "row-1")));
|
|
||||||
assert!(!under.matches(&address("p", "t", "row-1")));
|
|
||||||
assert!(!under.matches(&address("p", "s", "col-1")));
|
|
||||||
assert!(!under.matches(&address("p", "s", "ro")));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_record_interest_matches_only_its_address() {
|
|
||||||
let interest = Interest::Record(address("p", "s", "k"));
|
|
||||||
assert!(interest.matches(&address("p", "s", "k")));
|
|
||||||
assert!(!interest.matches(&address("p", "s", "k2")));
|
|
||||||
assert!(!interest.matches(&address("q", "s", "k")));
|
|
||||||
assert!(Interest::Prefix(prefix("p", "s", "k")).matches(&address("p", "s", "k2")));
|
|
||||||
assert!(!Interest::Prefix(prefix("p", "s", "k")).matches(&address("p", "s", "j")));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,26 +0,0 @@
|
||||||
//! A provider record's value as core sees it. Core holds no bytes and no reader of them: a state
|
|
||||||
//! port implementation decodes a record with its schema's member names (the `thing-state` crate)
|
|
||||||
//! and hands core this tree.
|
|
||||||
|
|
||||||
/// A provider record's value: closed, ordered and named, with no case folding.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub enum StateValue {
|
|
||||||
Nil,
|
|
||||||
Bool(bool),
|
|
||||||
Int(i128),
|
|
||||||
Float(f64),
|
|
||||||
Text(String),
|
|
||||||
Bytes(Vec<u8>),
|
|
||||||
List(Vec<StateValue>),
|
|
||||||
Record(Vec<(String, StateValue)>),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl StateValue {
|
|
||||||
/// The member of a `Record` by exact name; `None` for any other shape or a missing name.
|
|
||||||
pub fn member(&self, name: &str) -> Option<&StateValue> {
|
|
||||||
match self {
|
|
||||||
StateValue::Record(members) => members.iter().find(|(member, _)| member == name).map(|(_, value)| value),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,37 +0,0 @@
|
||||||
//! The closed render-command list. Paint order is emission order: nothing carries a stacking value
|
|
||||||
//! or an escape hatch. Coordinates are f32 logical px (Pixels) or cells (Cells), already divided
|
|
||||||
//! by the scale; colours are literals, so a theme token cannot reach a backend by type.
|
|
||||||
|
|
||||||
use thing_contract::Rgba;
|
|
||||||
|
|
||||||
use crate::layout::{Rect, Run};
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub enum RenderCommand {
|
|
||||||
FillRect { rect: Rect, radius: f32, color: Rgba },
|
|
||||||
StrokeRect { rect: Rect, radius: f32, width: f32, color: Rgba },
|
|
||||||
/// One line of text at `origin` (its top-left).
|
|
||||||
Text { origin: (f32, f32), run: Run, color: Rgba },
|
|
||||||
Image { rect: Rect, uri: String, alt: String },
|
|
||||||
ClipPush { rect: Rect, radius: f32 },
|
|
||||||
ClipPop,
|
|
||||||
Polyline { points: Vec<(f32, f32)>, width: f32, color: Rgba },
|
|
||||||
Polygon { points: Vec<(f32, f32)>, color: Rgba },
|
|
||||||
Embed { rect: Rect, slot_kind: String, slot_id: String },
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether every ClipPush has its ClipPop, nested, and no ClipPop comes first.
|
|
||||||
pub fn balanced(commands: &[RenderCommand]) -> bool {
|
|
||||||
let mut open = 0usize;
|
|
||||||
for command in commands {
|
|
||||||
match command {
|
|
||||||
RenderCommand::ClipPush { .. } => open += 1,
|
|
||||||
RenderCommand::ClipPop => match open.checked_sub(1) {
|
|
||||||
Some(rest) => open = rest,
|
|
||||||
None => return false,
|
|
||||||
},
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
open == 0
|
|
||||||
}
|
|
||||||
|
|
@ -1,187 +0,0 @@
|
||||||
//! The leaves: control chrome, an Image's fit and the missing-asset placeholder. Core alone turns
|
|
||||||
//! fit and control state into geometry; no caret, selection or focus ring (those need edit and
|
|
||||||
//! focus state). Pixels and Cells share the lowering; only the inset and the stroke differ.
|
|
||||||
|
|
||||||
use std::borrow::Cow;
|
|
||||||
|
|
||||||
use thing_contract::{ButtonNode, ImageFit, ImageNode, NodeId, SelectNode, SliderNode, TextInputNode, ToggleNode};
|
|
||||||
|
|
||||||
use super::Painter;
|
|
||||||
use super::command::RenderCommand;
|
|
||||||
use crate::bind::{Bound, Field};
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
use crate::input::drafts::current;
|
|
||||||
use crate::layout::{ControlForm, LaidControl, Measure, Metrics, Rect, TextRequest};
|
|
||||||
|
|
||||||
/// Where an Image lands inside `rect` for an extent of `(w, h)` asset px (1 asset px = 1 logical
|
|
||||||
/// px), and whether it must be clipped to `rect`.
|
|
||||||
fn fitted(fit: &ImageFit, rect: Rect, (w, h): (f32, f32)) -> (Rect, bool) {
|
|
||||||
let scale = match fit {
|
|
||||||
ImageFit::Fill => return (rect, false),
|
|
||||||
ImageFit::Contain => (rect.w / w).min(rect.h / h),
|
|
||||||
ImageFit::Cover => (rect.w / w).max(rect.h / h),
|
|
||||||
ImageFit::Unscaled => 1.0,
|
|
||||||
};
|
|
||||||
let (dw, dh) = (w * scale, h * scale);
|
|
||||||
let dest = Rect { x: rect.x + (rect.w - dw) / 2.0, y: rect.y + (rect.h - dh) / 2.0, w: dw, h: dh };
|
|
||||||
(dest, matches!(fit, ImageFit::Cover | ImageFit::Unscaled))
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> Painter<'a> {
|
|
||||||
/// What the site shows: its draft over its bound value, the one read every control makes.
|
|
||||||
fn shown(&self, id: &NodeId, field: Field) -> Option<Cow<'a, Bound>> {
|
|
||||||
current(self.tree, self.input.session.drafts, id, field)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn flag(&self, id: &NodeId, field: Field) -> Option<bool> {
|
|
||||||
match self.shown(id, field).as_deref() {
|
|
||||||
Some(Bound::Bool(b)) => Some(*b),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn shown_text(&self, id: &NodeId, field: Field) -> Option<String> {
|
|
||||||
match self.shown(id, field).as_deref() {
|
|
||||||
Some(Bound::Text(t)) => Some(t.clone()),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn stroke(&mut self, id: &NodeId, rect: Rect) {
|
|
||||||
let color = self.named(id, "thing.control.border");
|
|
||||||
self.out.commands.push(RenderCommand::StrokeRect { rect, radius: 0.0, width: 1.0, color });
|
|
||||||
}
|
|
||||||
|
|
||||||
fn fill(&mut self, id: &NodeId, rect: Rect, token: &str) {
|
|
||||||
let color = self.named(id, token);
|
|
||||||
self.out.commands.push(RenderCommand::FillRect { rect, radius: 0.0, color });
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The lines of `content` the engine breaks at `at.w`, those that end within `room` of the top.
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
|
||||||
pub(super) fn draw_text(&mut self, id: &NodeId, content: &str, token: &str, wrap: bool, max_lines: Option<u32>, at: Rect, room: f32, text: &mut dyn Measure) {
|
|
||||||
let color = match self.input.theme.text.get(token) {
|
|
||||||
Some(style) => style.color.clone(),
|
|
||||||
None => self.fault(id, token),
|
|
||||||
};
|
|
||||||
let request = TextRequest { node: id, text: content, style_token: token, wrap, max_lines };
|
|
||||||
for line in text.text(&request, at.w).lines.into_iter().filter(|line| line.y + line.height <= room) {
|
|
||||||
self.out.commands.push(RenderCommand::Text { origin: (at.x, at.y + line.y), run: line.run, color: color.clone() });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What stands where a leaf's content could not be drawn: a fill and an error stroke.
|
|
||||||
pub(super) fn placeholder(&mut self, id: &NodeId, rect: Rect) {
|
|
||||||
self.fill(id, rect, "thing.placeholder");
|
|
||||||
let color = self.named(id, "thing.error");
|
|
||||||
self.out.commands.push(RenderCommand::StrokeRect { rect, radius: 0.0, width: 1.0, color });
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A control's chrome as layout chose its form: `Bordered` is the box stroke; `Compact` is the
|
|
||||||
/// one-row affordance on the first row, whose stroke is the brackets of a one-row stroke.
|
|
||||||
fn chrome(&mut self, id: &NodeId, rect: Rect, form: ControlForm) {
|
|
||||||
match form {
|
|
||||||
ControlForm::Bordered => self.stroke(id, rect),
|
|
||||||
ControlForm::Compact => self.stroke(id, Rect { h: rect.h.min(1.0), ..rect }),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn button(&mut self, n: &ButtonNode, rect: Rect, control: LaidControl) {
|
|
||||||
let id = &n.common.id;
|
|
||||||
let busy = self.input.session.states.is_some_and(|states| states.get(id).busy);
|
|
||||||
let enabled = self.flag(id, Field::Enabled) != Some(false) && !busy;
|
|
||||||
self.fill(id, rect, if enabled { "thing.control.fill" } else { "thing.control.disabled" });
|
|
||||||
self.chrome(id, rect, control.form);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn toggle(&mut self, n: &ToggleNode, rect: Rect, control: LaidControl) {
|
|
||||||
let id = &n.common.id;
|
|
||||||
let LaidControl { form, content } = control;
|
|
||||||
// A compact toggle is its glyph alone, on the one row its form keeps.
|
|
||||||
let inner = match form {
|
|
||||||
ControlForm::Bordered => content,
|
|
||||||
ControlForm::Compact => Rect { h: content.h.min(1.0), ..content },
|
|
||||||
};
|
|
||||||
if form == ControlForm::Bordered {
|
|
||||||
self.chrome(id, rect, form);
|
|
||||||
}
|
|
||||||
let side = inner.h.min(inner.w / 2.0).max(0.0);
|
|
||||||
let checked = self.flag(id, Field::Checked) == Some(true);
|
|
||||||
let x = if checked { inner.x + inner.w - side } else { inner.x };
|
|
||||||
self.fill(id, Rect { x, y: inner.y + (inner.h - side) / 2.0, w: side, h: side }, "thing.control.accent");
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn slider(&mut self, n: &SliderNode, rect: Rect) {
|
|
||||||
let id = &n.common.id;
|
|
||||||
let thickness = if self.input.metrics == Metrics::Cells { rect.h } else { rect.h / 4.0 };
|
|
||||||
self.fill(id, Rect { x: rect.x, y: rect.y + (rect.h - thickness) / 2.0, w: rect.w, h: thickness }, "thing.control.border");
|
|
||||||
let fraction = if n.min.is_finite() && n.max.is_finite() && n.min < n.max {
|
|
||||||
match self.shown(id, Field::Value).as_deref() {
|
|
||||||
Some(Bound::Number(v)) if v.is_finite() => ((v - n.min) / (n.max - n.min)).clamp(0.0, 1.0),
|
|
||||||
_ => 0.0,
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
self.out.diagnostics.push(Diagnostic {
|
|
||||||
code: Code::StyleValueInvalid,
|
|
||||||
surface: self.tree.resolved().document().record_key(),
|
|
||||||
node: Some(id.clone()),
|
|
||||||
detail: "max".to_string(),
|
|
||||||
});
|
|
||||||
0.0
|
|
||||||
};
|
|
||||||
let side = rect.h.min(rect.w).max(0.0);
|
|
||||||
let x = rect.x + (rect.w - side) * fraction as f32;
|
|
||||||
self.fill(id, Rect { x, y: rect.y, w: side, h: side }, "thing.control.accent");
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn select(&mut self, n: &SelectNode, rect: Rect, control: LaidControl, text: &mut dyn Measure) {
|
|
||||||
let id = &n.common.id;
|
|
||||||
let inner = control.content;
|
|
||||||
self.chrome(id, rect, control.form);
|
|
||||||
let Some(value) = self.shown_text(id, Field::Selected) else { return };
|
|
||||||
let tree = self.tree;
|
|
||||||
let label = match tree.value(id, Field::Options) {
|
|
||||||
Some(Bound::Options(options)) => options.iter().find(|o| o.value == value).map_or(value.as_str(), |o| o.label.as_str()),
|
|
||||||
_ => value.as_str(),
|
|
||||||
};
|
|
||||||
self.draw_text(id, label, "thing.text", false, Some(1), inner, inner.h, text);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn text_input(&mut self, n: &TextInputNode, rect: Rect, control: LaidControl, text: &mut dyn Measure) {
|
|
||||||
let id = &n.common.id;
|
|
||||||
let inner = control.content;
|
|
||||||
self.chrome(id, rect, control.form);
|
|
||||||
let (content, token) = match self.shown_text(id, Field::Initial).filter(|t| !t.is_empty()) {
|
|
||||||
Some(initial) => (initial, "thing.text"),
|
|
||||||
None => match self.shown_text(id, Field::Placeholder) {
|
|
||||||
Some(placeholder) => (placeholder, "thing.text.placeholder"),
|
|
||||||
None => return,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
self.draw_text(id, &content, token, n.multiline, if n.multiline { None } else { Some(1) }, inner, inner.h, text);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn image(&mut self, n: &ImageNode, rect: Rect, text: &mut dyn Measure) {
|
|
||||||
let id = &n.common.id;
|
|
||||||
let alt = self.shown_text(id, Field::Alt).unwrap_or_default();
|
|
||||||
let tree = self.tree;
|
|
||||||
let entry = match tree.value(id, Field::Asset) {
|
|
||||||
Some(Bound::Asset(entry)) if entry.width.get() > 0 && entry.height.get() > 0 => entry,
|
|
||||||
_ => {
|
|
||||||
self.placeholder(id, rect);
|
|
||||||
if !alt.is_empty() && rect.w > 0.0 {
|
|
||||||
self.draw_text(id, &alt, "thing.text", true, Some(1), rect, rect.h, text);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let (dest, clipped) = fitted(&n.fit, rect, (entry.width.get() as f32, entry.height.get() as f32));
|
|
||||||
if clipped {
|
|
||||||
self.out.commands.push(RenderCommand::ClipPush { rect, radius: 0.0 });
|
|
||||||
}
|
|
||||||
self.out.commands.push(RenderCommand::Image { rect: dest, uri: entry.uri.clone(), alt });
|
|
||||||
if clipped {
|
|
||||||
self.out.commands.push(RenderCommand::ClipPop);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,336 +0,0 @@
|
||||||
//! Render: a `BoundTree`, its `LaidTree`, the scroll offsets and a theme become the closed command
|
|
||||||
//! list and the placed geometry hit-test, IME and accessibility read. A pure function: it reads
|
|
||||||
//! no port, no clock and no state, and equal inputs give an equal `Rendered`.
|
|
||||||
//!
|
|
||||||
//! This is the one place device px become logical px (divided by the scale) and scroll offsets
|
|
||||||
//! apply. Paint order is `LaidTree` order, which layout owns; render only looks nodes up.
|
|
||||||
|
|
||||||
mod command;
|
|
||||||
mod leaf;
|
|
||||||
mod plot;
|
|
||||||
mod scroll;
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
use thing_contract::{Anchor, BoxNode, ColorRef, Node, NodeId, Rgba};
|
|
||||||
|
|
||||||
pub use command::{RenderCommand, balanced};
|
|
||||||
pub use scroll::{ScrollOffsets, clamp};
|
|
||||||
|
|
||||||
use crate::bind::{Bound, BoundTree, Field};
|
|
||||||
use crate::command::NodeStates;
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
use crate::input::Drafts;
|
|
||||||
use crate::layout::{ControlForm, LaidControl, LaidNode, LaidTree, MAX_DEVICE, Measure, Metrics, Rect};
|
|
||||||
use crate::theme::{Theme, fallback};
|
|
||||||
|
|
||||||
/// What a frame is drawn with. `viewport` is what layout was given (logical px or cells).
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
pub struct RenderInput<'a> {
|
|
||||||
pub scale: f32,
|
|
||||||
pub metrics: Metrics,
|
|
||||||
pub viewport: (f32, f32),
|
|
||||||
pub scroll: &'a ScrollOffsets,
|
|
||||||
pub theme: &'a Theme,
|
|
||||||
pub session: Session<'a>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What the user has done that the documents and state do not say: the drafts that draw over bound
|
|
||||||
/// values, and the node states (busy, marked) commands derived. `Session::EMPTY` is a surface nobody
|
|
||||||
/// has touched; a frame drawn with it is the frame the bound tree alone gives.
|
|
||||||
#[derive(Clone, Copy, Debug)]
|
|
||||||
pub struct Session<'a> {
|
|
||||||
pub drafts: Option<&'a Drafts>,
|
|
||||||
pub states: Option<&'a NodeStates>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Session<'static> {
|
|
||||||
pub const EMPTY: Session<'static> = Session { drafts: None, states: None };
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> Session<'a> {
|
|
||||||
pub fn new(drafts: &'a Drafts, states: &'a NodeStates) -> Self {
|
|
||||||
Self { drafts: Some(drafts), states: Some(states) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A laid node as it is on screen. `rect` is the scrolled border box in logical px (cells);
|
|
||||||
/// `visible` is `rect` cut by the clips open around it, `None` when nothing of it shows.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct Placed {
|
|
||||||
pub id: NodeId,
|
|
||||||
pub rect: Rect,
|
|
||||||
pub visible: Option<Rect>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The frame: commands in paint order, `placed` in the same order, and the diagnostics of the
|
|
||||||
/// frame (layout's, then render's).
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct Rendered {
|
|
||||||
pub commands: Vec<RenderCommand>,
|
|
||||||
pub placed: Vec<Placed>,
|
|
||||||
pub diagnostics: Vec<Diagnostic>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Device px per logical px: the scale in Pixels when it is finite and positive, else 1; always 1 in
|
|
||||||
/// Cells. The one owner of the rule: render divides by it, and input multiplies by it.
|
|
||||||
pub(crate) fn device_scale(metrics: Metrics, scale: f32) -> f32 {
|
|
||||||
match metrics {
|
|
||||||
Metrics::Pixels if scale.is_finite() && scale > 0.0 => scale,
|
|
||||||
_ => 1.0,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn render(tree: &BoundTree, laid: &LaidTree, input: &RenderInput, text: &mut dyn Measure) -> Rendered {
|
|
||||||
let nodes = tree.index();
|
|
||||||
let k = device_scale(input.metrics, input.scale);
|
|
||||||
let mut ids = HashMap::new();
|
|
||||||
for (i, node) in laid.nodes.iter().enumerate() {
|
|
||||||
ids.entry(&node.id).or_insert(i);
|
|
||||||
}
|
|
||||||
let mut painter = Painter {
|
|
||||||
tree,
|
|
||||||
laid,
|
|
||||||
input,
|
|
||||||
nodes,
|
|
||||||
ids,
|
|
||||||
k,
|
|
||||||
shift: Vec::with_capacity(laid.nodes.len()),
|
|
||||||
inner: Vec::with_capacity(laid.nodes.len()),
|
|
||||||
stack: Vec::new(),
|
|
||||||
clips: Vec::new(),
|
|
||||||
out: Rendered { commands: Vec::new(), placed: Vec::new(), diagnostics: laid.diagnostics.clone() },
|
|
||||||
};
|
|
||||||
for i in 0..laid.nodes.len() {
|
|
||||||
painter.enter(i, text);
|
|
||||||
}
|
|
||||||
while let Some(top) = painter.stack.pop() {
|
|
||||||
painter.close(top);
|
|
||||||
}
|
|
||||||
painter.out
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Painter<'a> {
|
|
||||||
tree: &'a BoundTree,
|
|
||||||
laid: &'a LaidTree,
|
|
||||||
input: &'a RenderInput<'a>,
|
|
||||||
nodes: HashMap<&'a NodeId, &'a Node>,
|
|
||||||
ids: HashMap<&'a NodeId, usize>,
|
|
||||||
k: f32,
|
|
||||||
/// Per laid node so far: the device translation it is drawn under, and the one its children
|
|
||||||
/// are drawn under (that minus its own clamped offset).
|
|
||||||
shift: Vec<(f32, f32)>,
|
|
||||||
inner: Vec<(f32, f32)>,
|
|
||||||
/// The open nodes, a chain of ancestors; and the scrolled padding boxes of the open clips.
|
|
||||||
stack: Vec<usize>,
|
|
||||||
clips: Vec<Rect>,
|
|
||||||
out: Rendered,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn meet(a: Rect, b: Rect) -> Option<Rect> {
|
|
||||||
let (x0, y0) = (a.x.max(b.x), a.y.max(b.y));
|
|
||||||
let (x1, y1) = ((a.x + a.w).min(b.x + b.w), (a.y + a.h).min(b.y + b.h));
|
|
||||||
(x1 >= x0 && y1 >= y0).then_some(Rect { x: x0, y: y0, w: x1 - x0, h: y1 - y0 })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether layout states the node a `Compact` control, whose content is clipped to its rect.
|
|
||||||
fn is_compact(node: &LaidNode) -> bool {
|
|
||||||
node.control.is_some_and(|c| c.form == ControlForm::Compact)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn radius(value: f64) -> f32 {
|
|
||||||
let value = value as f32;
|
|
||||||
if value.is_finite() && value > 0.0 { value } else { 0.0 }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A thumb along one axis: the track starts at `start` and is `track` long, the content reaches
|
|
||||||
/// `max` past it, and the view is `offset` in. Returns the thumb's start and length.
|
|
||||||
fn thumb_span(start: f32, track: f32, max: f32, offset: f32) -> (f32, f32) {
|
|
||||||
let length = track * track / (track + max);
|
|
||||||
(start + (track - length) * offset / max, length)
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> Painter<'a> {
|
|
||||||
fn logical(&self, rect: Rect, shift: (f32, f32)) -> Rect {
|
|
||||||
let k = self.k;
|
|
||||||
Rect { x: (rect.x + shift.0) / k, y: (rect.y + shift.1) / k, w: rect.w / k, h: rect.h / k }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn fault(&mut self, node: &NodeId, token: &str) -> Rgba {
|
|
||||||
self.out.diagnostics.push(Diagnostic {
|
|
||||||
code: Code::ThemeTokenUnknown,
|
|
||||||
surface: self.tree.resolved().document().record_key(),
|
|
||||||
node: Some(node.clone()),
|
|
||||||
detail: token.to_string(),
|
|
||||||
});
|
|
||||||
fallback()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn color(&mut self, node: &NodeId, color: &ColorRef) -> Rgba {
|
|
||||||
match (self.input.theme.resolve(color), color) {
|
|
||||||
(Some(rgba), _) => rgba,
|
|
||||||
(None, ColorRef::Token(token)) => self.fault(node, &token.name),
|
|
||||||
(None, ColorRef::Rgba(literal)) => literal.clone(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn named(&mut self, node: &NodeId, name: &str) -> Rgba {
|
|
||||||
match self.input.theme.color(name) {
|
|
||||||
Some(rgba) => rgba,
|
|
||||||
None => self.fault(node, name),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The border a Box draws: its colour and width, when it has a legal width.
|
|
||||||
fn border(&self, b: &'a BoxNode) -> Option<(&'a ColorRef, f32)> {
|
|
||||||
let border = b.paint.border.as_ref()?;
|
|
||||||
let width = border.width as f32;
|
|
||||||
(width.is_finite() && width > 0.0 && width * self.k <= MAX_DEVICE).then_some((&border.color, width))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn enter(&mut self, i: usize, text: &mut dyn Measure) {
|
|
||||||
let tree = self.laid;
|
|
||||||
let laid = &tree.nodes[i];
|
|
||||||
let parent = laid.parent.map(|p| p as usize);
|
|
||||||
while let Some(&top) = self.stack.last() {
|
|
||||||
if Some(top) == parent {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
self.stack.pop();
|
|
||||||
self.close(top);
|
|
||||||
}
|
|
||||||
let node = self.nodes.get(&laid.id).copied();
|
|
||||||
let shift = match (parent, node) {
|
|
||||||
(Some(p), _) => self.inner[p],
|
|
||||||
// An overlay root is carried by what its anchor is carried by, never by the anchor's own scroll.
|
|
||||||
(None, Some(Node::Overlay(o))) => match &o.anchor {
|
|
||||||
Anchor::Node(anchor) => match self.ids.get(&anchor.node) {
|
|
||||||
Some(&a) if a < i => self.shift[a],
|
|
||||||
_ => (0.0, 0.0),
|
|
||||||
},
|
|
||||||
Anchor::Viewport => (0.0, 0.0),
|
|
||||||
},
|
|
||||||
(None, _) => (0.0, 0.0),
|
|
||||||
};
|
|
||||||
let own = self.input.scroll.of(laid);
|
|
||||||
self.shift.push(shift);
|
|
||||||
self.inner.push((shift.0 - own.0, shift.1 - own.1));
|
|
||||||
|
|
||||||
let rect = self.logical(laid.rect, shift);
|
|
||||||
let visible = self.clips.iter().try_fold(rect, |seen, clip| meet(seen, *clip));
|
|
||||||
self.out.placed.push(Placed { id: laid.id.clone(), rect, visible });
|
|
||||||
self.stack.push(i);
|
|
||||||
let Some(node) = node else { return };
|
|
||||||
let control = laid.control.map(|c| LaidControl { content: self.logical(c.content, shift), ..c });
|
|
||||||
self.paint(node, rect, control, text);
|
|
||||||
// A fault commands left on the node shows over its own paint, under what is inside it.
|
|
||||||
if self.input.session.states.is_some_and(|states| states.get(&laid.id).mark.is_some()) {
|
|
||||||
let color = self.named(&laid.id, "thing.error");
|
|
||||||
self.out.commands.push(RenderCommand::StrokeRect { rect, radius: 0.0, width: 1.0, color });
|
|
||||||
}
|
|
||||||
if let (Some(padding), Node::Box(b)) = (laid.clip, node) {
|
|
||||||
let clip = self.logical(padding, shift);
|
|
||||||
let border = self.border(b).map_or(0.0, |(_, width)| width);
|
|
||||||
self.out.commands.push(RenderCommand::ClipPush { rect: clip, radius: (radius(b.paint.radius) - border).max(0.0) });
|
|
||||||
self.clips.push(clip);
|
|
||||||
} else if is_compact(laid) {
|
|
||||||
// A Compact control's content may run past its last row: cut it to the rect the form states.
|
|
||||||
self.out.commands.push(RenderCommand::ClipPush { rect, radius: 0.0 });
|
|
||||||
self.clips.push(rect);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn paint(&mut self, node: &'a Node, rect: Rect, control: Option<LaidControl>, text: &mut dyn Measure) {
|
|
||||||
match node {
|
|
||||||
Node::Box(b) => {
|
|
||||||
let id = &b.common.id;
|
|
||||||
if let Some(background) = &b.paint.background {
|
|
||||||
let color = self.color(id, background);
|
|
||||||
self.out.commands.push(RenderCommand::FillRect { rect, radius: radius(b.paint.radius), color });
|
|
||||||
}
|
|
||||||
if let Some((color, width)) = self.border(b) {
|
|
||||||
let color = self.color(id, color);
|
|
||||||
self.out.commands.push(RenderCommand::StrokeRect { rect, radius: radius(b.paint.radius), width, color });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Node::Overlay(o) if o.modal => {
|
|
||||||
let color = self.named(&o.common.id, "thing.scrim");
|
|
||||||
let (w, h) = self.input.viewport;
|
|
||||||
self.out.commands.push(RenderCommand::FillRect { rect: Rect { x: 0.0, y: 0.0, w, h }, radius: 0.0, color });
|
|
||||||
}
|
|
||||||
Node::Embed(e) => {
|
|
||||||
let (slot_kind, slot_id) = (e.slot_kind.clone(), e.slot_id.clone());
|
|
||||||
self.out.commands.push(RenderCommand::Embed { rect, slot_kind, slot_id });
|
|
||||||
}
|
|
||||||
Node::Use(u) => self.placeholder(&u.common.id, rect),
|
|
||||||
Node::Text(n) => {
|
|
||||||
let tree = self.tree;
|
|
||||||
match tree.value(&n.common.id, Field::Content) {
|
|
||||||
Some(Bound::Text(content)) => {
|
|
||||||
let max_lines = n.max_lines.map(|lines| lines.get().max(0) as u32);
|
|
||||||
self.draw_text(&n.common.id, content, &n.style_token, n.wrap, max_lines, rect, f32::INFINITY, text);
|
|
||||||
}
|
|
||||||
Some(Bound::Error(_)) => {
|
|
||||||
let color = self.named(&n.common.id, "thing.error");
|
|
||||||
self.out.commands.push(RenderCommand::StrokeRect { rect, radius: 0.0, width: 1.0, color });
|
|
||||||
}
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// A control layout states no form for has nothing to draw as.
|
|
||||||
Node::Button(n) => match control {
|
|
||||||
Some(c) => self.button(n, rect, c),
|
|
||||||
None => self.placeholder(&n.common.id, rect),
|
|
||||||
},
|
|
||||||
Node::Toggle(n) => match control {
|
|
||||||
Some(c) => self.toggle(n, rect, c),
|
|
||||||
None => self.placeholder(&n.common.id, rect),
|
|
||||||
},
|
|
||||||
Node::Slider(n) => self.slider(n, rect),
|
|
||||||
Node::Select(n) => match control {
|
|
||||||
Some(c) => self.select(n, rect, c, text),
|
|
||||||
None => self.placeholder(&n.common.id, rect),
|
|
||||||
},
|
|
||||||
Node::TextInput(n) => match control {
|
|
||||||
Some(c) => self.text_input(n, rect, c, text),
|
|
||||||
None => self.placeholder(&n.common.id, rect),
|
|
||||||
},
|
|
||||||
Node::Image(n) => self.image(n, rect, text),
|
|
||||||
Node::Plot(n) => self.plot(n, rect),
|
|
||||||
Node::Overlay(_) | Node::Repeat(_) | Node::Slot(_) => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Close an open node: its clip, then its scrollbars (which the clip does not cut).
|
|
||||||
fn close(&mut self, i: usize) {
|
|
||||||
let laid = self.laid;
|
|
||||||
let node = &laid.nodes[i];
|
|
||||||
let Some(padding) = node.clip else {
|
|
||||||
if is_compact(node) {
|
|
||||||
self.clips.pop();
|
|
||||||
self.out.commands.push(RenderCommand::ClipPop);
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
};
|
|
||||||
self.clips.pop();
|
|
||||||
self.out.commands.push(RenderCommand::ClipPop);
|
|
||||||
let Some(max) = node.max_scroll else { return };
|
|
||||||
let offset = self.input.scroll.of(node);
|
|
||||||
let thickness = match self.input.metrics {
|
|
||||||
Metrics::Cells => 1.0,
|
|
||||||
Metrics::Pixels => self.input.theme.scrollbar.max(0.0),
|
|
||||||
} * self.k;
|
|
||||||
let shift = self.shift[i];
|
|
||||||
let thumb = self.named(&node.id, "thing.scrollbar.thumb");
|
|
||||||
if max.1 > 0.0 {
|
|
||||||
let (y, h) = thumb_span(padding.y, padding.h, max.1, offset.1);
|
|
||||||
let rect = self.logical(Rect { x: padding.x + padding.w - thickness, y, w: thickness, h }, shift);
|
|
||||||
self.out.commands.push(RenderCommand::FillRect { rect, radius: 0.0, color: thumb.clone() });
|
|
||||||
}
|
|
||||||
if max.0 > 0.0 {
|
|
||||||
let (x, w) = thumb_span(padding.x, padding.w, max.0, offset.0);
|
|
||||||
let rect = self.logical(Rect { x, y: padding.y + padding.h - thickness, w, h: thickness }, shift);
|
|
||||||
self.out.commands.push(RenderCommand::FillRect { rect, radius: 0.0, color: thumb });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,173 +0,0 @@
|
||||||
//! A Plot lowered to geometry: the domain, then Polylines, Polygons or FillRects. Pure and
|
|
||||||
//! bounded: a series of N points gives at most N vertices (Line), 2N (Area: each run of m >= 2
|
|
||||||
//! points adds two baseline vertices) or N rects (Bar); a non-finite or unrepresentable (f32) point is skipped with one diagnostic, never drawn.
|
|
||||||
|
|
||||||
use thing_contract::{PlotMark, PlotNode};
|
|
||||||
|
|
||||||
use super::Painter;
|
|
||||||
use super::command::RenderCommand;
|
|
||||||
use crate::bind::{Bound, Field};
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
use crate::layout::Rect;
|
|
||||||
|
|
||||||
/// One axis' domain: an explicit bound that is finite and not crossed by the other end is kept,
|
|
||||||
/// anything else takes the data value and is named; equal ends widen by 1 each way.
|
|
||||||
fn domain(explicit: (Option<f64>, Option<f64>), data: (f64, f64), names: (&'static str, &'static str), invalid: &mut Vec<&'static str>) -> (f64, f64) {
|
|
||||||
let (mut lo, mut hi) = (explicit.0.filter(|v| v.is_finite()), explicit.1.filter(|v| v.is_finite()));
|
|
||||||
if explicit.0.is_some() && lo.is_none() {
|
|
||||||
invalid.push(names.0);
|
|
||||||
}
|
|
||||||
if explicit.1.is_some() && hi.is_none() {
|
|
||||||
invalid.push(names.1);
|
|
||||||
}
|
|
||||||
if let (Some(a), Some(b)) = (lo, hi) {
|
|
||||||
if a > b {
|
|
||||||
invalid.extend([names.0, names.1]);
|
|
||||||
(lo, hi) = (None, None);
|
|
||||||
}
|
|
||||||
} else if let Some(a) = lo {
|
|
||||||
if a > data.1 {
|
|
||||||
invalid.push(names.0);
|
|
||||||
lo = None;
|
|
||||||
}
|
|
||||||
} else if let Some(b) = hi {
|
|
||||||
if b < data.0 {
|
|
||||||
invalid.push(names.1);
|
|
||||||
hi = None;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let (lo, hi) = (lo.unwrap_or(data.0), hi.unwrap_or(data.1));
|
|
||||||
if lo == hi { (lo - 1.0, hi + 1.0) } else { (lo, hi) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where the series lands in `rect`: screen y grows down.
|
|
||||||
struct Frame {
|
|
||||||
rect: Rect,
|
|
||||||
x: (f64, f64),
|
|
||||||
y: (f64, f64),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Frame {
|
|
||||||
/// A point of the series as f32 screen coordinates, `None` when either does not fit an f32.
|
|
||||||
fn at(&self, i: usize, v: f64) -> Option<(f32, f32)> {
|
|
||||||
let tx = halved(i as f64, self.x);
|
|
||||||
let x = (self.rect.x as f64 + tx * self.rect.w as f64) as f32;
|
|
||||||
let y = self.value(v) as f32;
|
|
||||||
(x.is_finite() && y.is_finite()).then_some((x, y))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Screen y of a value: y grows down. Halves keep a span near f64's range from overflowing.
|
|
||||||
fn value(&self, v: f64) -> f64 {
|
|
||||||
self.rect.y as f64 + self.rect.h as f64 - halved(v, self.y) * self.rect.h as f64
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where `v` falls in `(lo, hi)`, 0 to 1, computed on halves so `hi - lo` cannot overflow.
|
|
||||||
fn halved(v: f64, (lo, hi): (f64, f64)) -> f64 {
|
|
||||||
(v / 2.0 - lo / 2.0) / (hi / 2.0 - lo / 2.0)
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Painter<'_> {
|
|
||||||
pub(super) fn plot(&mut self, n: &thing_contract::PlotNode, rect: Rect) {
|
|
||||||
let tree = self.tree;
|
|
||||||
match tree.value(&n.common.id, Field::Series) {
|
|
||||||
Some(Bound::Series(values)) => self.plot_series(n, values, rect),
|
|
||||||
Some(Bound::Error(_)) => self.placeholder(&n.common.id, rect),
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A point that was not drawn is said once for the plot, whatever the reason.
|
|
||||||
fn dropped(&mut self, n: &PlotNode) {
|
|
||||||
self.out.diagnostics.push(Diagnostic {
|
|
||||||
code: Code::StyleValueInvalid,
|
|
||||||
surface: self.tree.resolved().document().record_key(),
|
|
||||||
node: Some(n.common.id.clone()),
|
|
||||||
detail: "series".to_string(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
fn plot_series(&mut self, n: &PlotNode, values: &[f64], rect: Rect) {
|
|
||||||
if values.is_empty() || !(rect.w > 0.0 && rect.h > 0.0) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let finite = || values.iter().copied().filter(|v| v.is_finite());
|
|
||||||
let low = finite().fold(f64::INFINITY, f64::min);
|
|
||||||
let high = finite().fold(f64::NEG_INFINITY, f64::max);
|
|
||||||
let data_y = if low <= high { (low, high) } else { (0.0, 0.0) };
|
|
||||||
let mut invalid = Vec::new();
|
|
||||||
let x = domain((n.x_min, n.x_max), (0.0, (values.len() - 1) as f64), ("x_min", "x_max"), &mut invalid);
|
|
||||||
let y = domain((n.y_min, n.y_max), data_y, ("y_min", "y_max"), &mut invalid);
|
|
||||||
for name in invalid {
|
|
||||||
self.out.diagnostics.push(Diagnostic {
|
|
||||||
code: Code::StyleValueInvalid,
|
|
||||||
surface: self.tree.resolved().document().record_key(),
|
|
||||||
node: Some(n.common.id.clone()),
|
|
||||||
detail: name.to_string(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
let frame = Frame { rect, x, y };
|
|
||||||
let color = self.named(&n.common.id, "thing.plot.mark");
|
|
||||||
let width = match self.input.metrics {
|
|
||||||
crate::layout::Metrics::Cells => 1.0,
|
|
||||||
crate::layout::Metrics::Pixels => 2.0,
|
|
||||||
};
|
|
||||||
let base = frame.value(0.0f64.clamp(y.0, y.1));
|
|
||||||
if !(base as f32).is_finite() {
|
|
||||||
self.dropped(n);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let mut shapes = Vec::new();
|
|
||||||
let mut dropped = false;
|
|
||||||
match n.mark {
|
|
||||||
PlotMark::Bar => {
|
|
||||||
let slot = rect.w / values.len() as f32;
|
|
||||||
for (i, v) in values.iter().enumerate() {
|
|
||||||
let top = frame.value(*v);
|
|
||||||
let (y0, y1) = (top.min(base) as f32, top.max(base) as f32);
|
|
||||||
let bar = Rect { x: rect.x + slot * i as f32, y: y0, w: slot, h: y1 - y0 };
|
|
||||||
if v.is_finite() && [bar.x, bar.y, bar.w, bar.h].iter().all(|c| c.is_finite()) {
|
|
||||||
shapes.push(RenderCommand::FillRect { rect: bar, radius: 0.0, color: color.clone() });
|
|
||||||
} else {
|
|
||||||
dropped = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
PlotMark::Line | PlotMark::Area => {
|
|
||||||
let mut run: Vec<(f32, f32)> = Vec::new();
|
|
||||||
let flush = |run: &mut Vec<(f32, f32)>, shapes: &mut Vec<RenderCommand>| {
|
|
||||||
if run.len() >= 2 {
|
|
||||||
let mut points = std::mem::take(run);
|
|
||||||
if n.mark == PlotMark::Area {
|
|
||||||
let (first, last) = (points[0].0, points[points.len() - 1].0);
|
|
||||||
points.extend([(last, base as f32), (first, base as f32)]);
|
|
||||||
shapes.push(RenderCommand::Polygon { points, color: color.clone() });
|
|
||||||
} else {
|
|
||||||
shapes.push(RenderCommand::Polyline { points, width, color: color.clone() });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
run.clear();
|
|
||||||
};
|
|
||||||
for (i, v) in values.iter().enumerate() {
|
|
||||||
match v.is_finite().then(|| frame.at(i, *v)).flatten() {
|
|
||||||
Some(point) => run.push(point),
|
|
||||||
None => {
|
|
||||||
dropped = true;
|
|
||||||
flush(&mut run, &mut shapes);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
flush(&mut run, &mut shapes);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if dropped {
|
|
||||||
self.dropped(n);
|
|
||||||
}
|
|
||||||
if shapes.is_empty() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
self.out.commands.push(RenderCommand::ClipPush { rect, radius: 0.0 });
|
|
||||||
self.out.commands.extend(shapes);
|
|
||||||
self.out.commands.push(RenderCommand::ClipPop);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,38 +0,0 @@
|
||||||
//! Scroll positions: runtime state, never a layout input. Input writes them here and render reads
|
|
||||||
//! them here, both through the one `clamp`.
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
use thing_contract::NodeId;
|
|
||||||
|
|
||||||
use crate::layout::LaidNode;
|
|
||||||
|
|
||||||
/// `offset` held within `[0, max_scroll]` on each axis; a NaN offset is 0, and an axis that
|
|
||||||
/// cannot scroll holds 0.
|
|
||||||
pub fn clamp(offset: (f32, f32), max_scroll: (f32, f32)) -> (f32, f32) {
|
|
||||||
let axis = |v: f32, max: f32| if v.is_nan() || !(max > 0.0 && max.is_finite()) { 0.0 } else { v.clamp(0.0, max) };
|
|
||||||
(axis(offset.0, max_scroll.0), axis(offset.1, max_scroll.1))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where each scroll node is scrolled to, in device px (Pixels) or cells (Cells), as written.
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq)]
|
|
||||||
pub struct ScrollOffsets(HashMap<NodeId, (f32, f32)>);
|
|
||||||
|
|
||||||
impl ScrollOffsets {
|
|
||||||
pub fn set(&mut self, node: NodeId, offset: (f32, f32)) {
|
|
||||||
self.0.insert(node, offset);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get(&self, node: &NodeId) -> Option<(f32, f32)> {
|
|
||||||
self.0.get(node).copied()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The offset a laid node is drawn at: what was written, clamped to what layout says it can
|
|
||||||
/// scroll. A node that does not scroll, or has no offset, has none.
|
|
||||||
pub fn of(&self, node: &LaidNode) -> (f32, f32) {
|
|
||||||
match (self.0.get(&node.id), node.max_scroll) {
|
|
||||||
(Some(offset), Some(max)) => clamp(*offset, max),
|
|
||||||
_ => (0.0, 0.0),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,597 +0,0 @@
|
||||||
//! The substitution: depth first, order preserving. A surface and a composition body go through
|
|
||||||
//! the same functions; the scope says whether a Param is bound.
|
|
||||||
//!
|
|
||||||
//! Expanded ids: inside the expansion of Use `u`, the body root takes `u`'s id and every other
|
|
||||||
//! body id `b` becomes `u/b`. Arguments are expanded in the caller's scope before the body sees
|
|
||||||
//! them, so a Slot argument's nodes keep the ids they had in the caller.
|
|
||||||
|
|
||||||
use std::collections::{HashMap, HashSet};
|
|
||||||
|
|
||||||
use thing_contract::*;
|
|
||||||
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
use crate::port::{Address, Lookup, Record, StatePort};
|
|
||||||
|
|
||||||
use super::{Limits, std as thing_std, validate};
|
|
||||||
|
|
||||||
/// The deepest input the expander recurses into. This is a stack bound and not the depth rule: the
|
|
||||||
/// rule (`Limits::max_tree_depth`) is judged by validate on the finished tree, where a slot argument
|
|
||||||
/// the body never places does not count. It exists because an in-memory tree from a Rust caller can
|
|
||||||
/// be deeper than any decoded document (CultCache bounds decoded nesting at 256), and recursion
|
|
||||||
/// over it would overflow the stack. The recursion grows its own stack (`super::grow`), so the bound
|
|
||||||
/// holds on any thread.
|
|
||||||
const STACK_BOUND: usize = 1024;
|
|
||||||
|
|
||||||
/// A fault the nearest enclosing Use turns into a placeholder (`Invalid`), or one that ends the
|
|
||||||
/// whole expansion (`Limit`, or `Stack` for input too deep to recurse into).
|
|
||||||
pub(super) enum Fault {
|
|
||||||
Invalid(String),
|
|
||||||
Limit(String),
|
|
||||||
Stack(String),
|
|
||||||
}
|
|
||||||
|
|
||||||
type Res<T> = Result<T, Fault>;
|
|
||||||
|
|
||||||
fn invalid<T>(detail: String) -> Res<T> {
|
|
||||||
Err(Fault::Invalid(detail))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The expansion of one composition body: the Use's id and common, and the finished arguments.
|
|
||||||
struct Scope {
|
|
||||||
use_id: NodeId,
|
|
||||||
root_id: NodeId,
|
|
||||||
use_visible: BoolSource,
|
|
||||||
use_a11y: Option<TextSource>,
|
|
||||||
args: HashMap<String, ArgValue>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) struct Expander<'a> {
|
|
||||||
port: &'a dyn StatePort,
|
|
||||||
limits: &'a Limits,
|
|
||||||
surface: String,
|
|
||||||
provider: &'a ProviderId,
|
|
||||||
commands: HashSet<&'a CommandId>,
|
|
||||||
pub diagnostics: Vec<Diagnostic>,
|
|
||||||
pub reads: HashSet<Address>,
|
|
||||||
nodes: usize,
|
|
||||||
stack: Vec<CompositionRef>,
|
|
||||||
current: Option<NodeId>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn arm_name(value: &ArgValue) -> &'static str {
|
|
||||||
match value {
|
|
||||||
ArgValue::Text(_) => "Text",
|
|
||||||
ArgValue::Number(_) => "Number",
|
|
||||||
ArgValue::Bool(_) => "Bool",
|
|
||||||
ArgValue::Bind(_) => "Bind",
|
|
||||||
ArgValue::Collection(_) => "Collection",
|
|
||||||
ArgValue::Command(_) => "Command",
|
|
||||||
ArgValue::Slot(_) => "Slot",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn kind_name(kind: &ParamKind) -> &'static str {
|
|
||||||
match kind {
|
|
||||||
ParamKind::Text => "Text",
|
|
||||||
ParamKind::Number => "Number",
|
|
||||||
ParamKind::Bool => "Bool",
|
|
||||||
ParamKind::Bind => "Bind",
|
|
||||||
ParamKind::Collection => "Collection",
|
|
||||||
ParamKind::Command => "Command",
|
|
||||||
ParamKind::Slot => "Slot",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn wrong_kind<T>(name: &ParamName, value: &ArgValue, position: &str) -> Res<T> {
|
|
||||||
invalid(format!("param '{}' is a {} argument, used as {position}", name.name, arm_name(value)))
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> Expander<'a> {
|
|
||||||
pub fn new(document: &'a SurfaceDocument, port: &'a dyn StatePort, limits: &'a Limits) -> Self {
|
|
||||||
Self {
|
|
||||||
port,
|
|
||||||
limits,
|
|
||||||
surface: document.record_key(),
|
|
||||||
provider: &document.provider_id,
|
|
||||||
commands: document.commands.iter().map(|declared| &declared.id).collect(),
|
|
||||||
diagnostics: Vec::new(),
|
|
||||||
reads: HashSet::new(),
|
|
||||||
nodes: 0,
|
|
||||||
stack: Vec::new(),
|
|
||||||
current: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn diag(&mut self, code: Code, node: Option<NodeId>, detail: impl Into<String>) {
|
|
||||||
self.diagnostics.push(Diagnostic { code, surface: self.surface.clone(), node, detail: detail.into() });
|
|
||||||
}
|
|
||||||
|
|
||||||
fn unbound(&mut self, what: &str) {
|
|
||||||
let node = self.current.clone();
|
|
||||||
self.diag(Code::UnboundParam, node, format!("{what} outside a composition"));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The surface root: no scope, no Use above it.
|
|
||||||
pub fn root(&mut self, root: &Node) -> Res<Node> {
|
|
||||||
self.node(root, None, 1, false)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- positions ----------------------------------------------------------------------
|
|
||||||
|
|
||||||
fn id(&self, id: &NodeId, scope: Option<&Scope>) -> NodeId {
|
|
||||||
match scope {
|
|
||||||
None => id.clone(),
|
|
||||||
Some(scope) if *id == scope.root_id => scope.use_id.clone(),
|
|
||||||
Some(scope) => NodeId::new(format!("{}/{}", scope.use_id.as_str(), id.as_str())),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn fill(&self, provider: &Option<ProviderId>) -> Option<ProviderId> {
|
|
||||||
Some(provider.clone().unwrap_or_else(|| self.provider.clone()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn bind(&self, bind: &Bind) -> Bind {
|
|
||||||
let source = match &bind.source {
|
|
||||||
StateSource::Record(state) => StateSource::Record(StateRef {
|
|
||||||
provider: self.fill(&state.provider),
|
|
||||||
schema: state.schema.clone(),
|
|
||||||
key: state.key.clone(),
|
|
||||||
}),
|
|
||||||
StateSource::Item => StateSource::Item,
|
|
||||||
};
|
|
||||||
Bind { source, member: bind.member.clone(), format: bind.format.clone() }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn arg_of<'s>(name: &ParamName, scope: &'s Scope) -> Res<&'s ArgValue> {
|
|
||||||
match scope.args.get(&name.name) {
|
|
||||||
Some(value) => Ok(value),
|
|
||||||
None => invalid(format!("the body names param '{}', which the composition does not declare", name.name)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn text(&mut self, source: &TextSource, scope: Option<&Scope>) -> Res<TextSource> {
|
|
||||||
Ok(match (source, scope) {
|
|
||||||
(TextSource::Literal(_), _) => source.clone(),
|
|
||||||
(TextSource::Bound(bind), _) => TextSource::Bound(self.bind(bind)),
|
|
||||||
(TextSource::Param(name), None) => {
|
|
||||||
self.unbound(&format!("param '{}'", name.name));
|
|
||||||
source.clone()
|
|
||||||
}
|
|
||||||
(TextSource::Param(name), Some(scope)) => match Self::arg_of(name, scope)? {
|
|
||||||
ArgValue::Text(arg) => TextSource::Literal(TextLiteral { value: arg.value.clone() }),
|
|
||||||
ArgValue::Bind(bind) => TextSource::Bound(bind.clone()),
|
|
||||||
other => return wrong_kind(name, other, "text"),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn number(&mut self, source: &NumberSource, scope: Option<&Scope>) -> Res<NumberSource> {
|
|
||||||
Ok(match (source, scope) {
|
|
||||||
(NumberSource::Literal(_), _) => source.clone(),
|
|
||||||
(NumberSource::Bound(bind), _) => NumberSource::Bound(self.bind(bind)),
|
|
||||||
(NumberSource::Param(name), None) => {
|
|
||||||
self.unbound(&format!("param '{}'", name.name));
|
|
||||||
source.clone()
|
|
||||||
}
|
|
||||||
(NumberSource::Param(name), Some(scope)) => match Self::arg_of(name, scope)? {
|
|
||||||
ArgValue::Number(arg) => NumberSource::Literal(NumberLiteral { value: arg.value }),
|
|
||||||
ArgValue::Bind(bind) => NumberSource::Bound(bind.clone()),
|
|
||||||
other => return wrong_kind(name, other, "a number"),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn boolean(&mut self, source: &BoolSource, scope: Option<&Scope>) -> Res<BoolSource> {
|
|
||||||
Ok(match (source, scope) {
|
|
||||||
(BoolSource::Literal(_), _) => source.clone(),
|
|
||||||
(BoolSource::Bound(bind), _) => BoolSource::Bound(self.bind(bind)),
|
|
||||||
(BoolSource::Param(name), None) => {
|
|
||||||
self.unbound(&format!("param '{}'", name.name));
|
|
||||||
source.clone()
|
|
||||||
}
|
|
||||||
(BoolSource::Param(name), Some(scope)) => match Self::arg_of(name, scope)? {
|
|
||||||
ArgValue::Bool(arg) => BoolSource::Literal(BoolLiteral { value: arg.value }),
|
|
||||||
ArgValue::Bind(bind) => BoolSource::Bound(bind.clone()),
|
|
||||||
other => return wrong_kind(name, other, "a bool"),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Substitution only: the form an argument takes, before any position judges it.
|
|
||||||
fn subst_collection(&mut self, source: &CollectionSource, scope: Option<&Scope>) -> Res<CollectionSource> {
|
|
||||||
Ok(match (source, scope) {
|
|
||||||
(CollectionSource::Records(records), _) => CollectionSource::Records(RecordsSource {
|
|
||||||
provider: self.fill(&records.provider),
|
|
||||||
schema: records.schema.clone(),
|
|
||||||
key_prefix: records.key_prefix.clone(),
|
|
||||||
}),
|
|
||||||
(CollectionSource::Member(bind), _) => CollectionSource::Member(self.bind(bind)),
|
|
||||||
(CollectionSource::Param(_), None) => source.clone(),
|
|
||||||
(CollectionSource::Param(name), Some(scope)) => match Self::arg_of(name, scope)? {
|
|
||||||
ArgValue::Collection(arg) => arg.source.clone(),
|
|
||||||
other => return wrong_kind(name, other, "a collection"),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn collection(&mut self, source: &CollectionSource, scope: Option<&Scope>) -> Res<CollectionSource> {
|
|
||||||
let found = self.subst_collection(source, scope)?;
|
|
||||||
if let CollectionSource::Param(name) = &found {
|
|
||||||
self.unbound(&format!("param '{}'", name.name));
|
|
||||||
}
|
|
||||||
Ok(found)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn subst_command(&mut self, command: &CommandRef, scope: Option<&Scope>) -> Res<CommandRef> {
|
|
||||||
Ok(match (command, scope) {
|
|
||||||
(_, None) => command.clone(),
|
|
||||||
(CommandRef::Id(id), Some(_)) => {
|
|
||||||
return invalid(format!(
|
|
||||||
"the body names command '{}'; a composition takes its commands as params",
|
|
||||||
id.id.as_str()
|
|
||||||
));
|
|
||||||
}
|
|
||||||
(CommandRef::Param(name), Some(scope)) => match Self::arg_of(name, scope)? {
|
|
||||||
ArgValue::Command(arg) => arg.command.clone(),
|
|
||||||
other => return wrong_kind(name, other, "a command"),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A command at its final position: declared by the surface, and no Param.
|
|
||||||
fn command(&mut self, command: &CommandRef, scope: Option<&Scope>) -> Res<CommandRef> {
|
|
||||||
let found = self.subst_command(command, scope)?;
|
|
||||||
match &found {
|
|
||||||
CommandRef::Id(id) if !self.commands.contains(&id.id) => {
|
|
||||||
let node = self.current.clone();
|
|
||||||
self.diag(Code::UndeclaredCommand, node, format!("command '{}' is not declared", id.id.as_str()));
|
|
||||||
}
|
|
||||||
CommandRef::Param(name) => self.unbound(&format!("param '{}'", name.name)),
|
|
||||||
CommandRef::Id(_) => {}
|
|
||||||
}
|
|
||||||
Ok(found)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn common(&mut self, common: &NodeCommon, scope: Option<&Scope>, root: bool) -> Res<NodeCommon> {
|
|
||||||
let id = self.id(&common.id, scope);
|
|
||||||
self.current = Some(id.clone());
|
|
||||||
match scope {
|
|
||||||
// A body root is the Use: its id, and its visibility and label unless the body labels it.
|
|
||||||
Some(scope) if root => {
|
|
||||||
if common.visible != BoolSource::Literal(BoolLiteral { value: true }) {
|
|
||||||
return invalid("the body root's visible is not the literal true; visibility is the Use's".into());
|
|
||||||
}
|
|
||||||
let a11y_label = match (&scope.use_a11y, &common.a11y_label) {
|
|
||||||
(Some(label), _) => Some(label.clone()),
|
|
||||||
(None, Some(label)) => Some(self.text(label, Some(scope))?),
|
|
||||||
(None, None) => None,
|
|
||||||
};
|
|
||||||
Ok(NodeCommon { id, visible: scope.use_visible.clone(), a11y_label })
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
let visible = self.boolean(&common.visible, scope)?;
|
|
||||||
let a11y_label = common.a11y_label.as_ref().map(|label| self.text(label, scope)).transpose()?;
|
|
||||||
Ok(NodeCommon { id, visible, a11y_label })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- nodes --------------------------------------------------------------------------
|
|
||||||
|
|
||||||
fn count(&mut self, added: usize) -> Res<()> {
|
|
||||||
self.nodes += added;
|
|
||||||
if self.nodes > self.limits.max_nodes {
|
|
||||||
return Err(Fault::Limit(format!("the expansion passed {} nodes", self.limits.max_nodes)));
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A child list. In a composition body a Slot is replaced by the nodes passed for it.
|
|
||||||
fn children(&mut self, list: &[Node], scope: Option<&Scope>, depth: usize) -> Res<Vec<Node>> {
|
|
||||||
let mut out = Vec::with_capacity(list.len());
|
|
||||||
for node in list {
|
|
||||||
match (node, scope) {
|
|
||||||
(Node::Slot(slot), Some(scope)) => match Self::arg_of(&slot.param, scope)? {
|
|
||||||
ArgValue::Slot(arg) => {
|
|
||||||
self.count(arg.nodes.iter().map(validate::size).sum())?;
|
|
||||||
out.extend(arg.nodes.iter().map(clone_deep));
|
|
||||||
}
|
|
||||||
other => return wrong_kind(&slot.param, other, "a slot"),
|
|
||||||
},
|
|
||||||
_ => out.push(self.node(node, scope, depth, false)?),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(out)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn node(&mut self, node: &Node, scope: Option<&Scope>, depth: usize, root: bool) -> Res<Node> {
|
|
||||||
super::grow(|| self.node_at(node, scope, depth, root))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn node_at(&mut self, node: &Node, scope: Option<&Scope>, depth: usize, root: bool) -> Res<Node> {
|
|
||||||
if depth > STACK_BOUND {
|
|
||||||
return Err(Fault::Stack(format!("the input nests deeper than {STACK_BOUND} levels")));
|
|
||||||
}
|
|
||||||
self.count(1)?;
|
|
||||||
// Each arm settles its own positions first and its child lists last: a diagnostic names the
|
|
||||||
// node being expanded, and a child list moves `current` on.
|
|
||||||
Ok(match node {
|
|
||||||
Node::Slot(slot) => match scope {
|
|
||||||
Some(_) => {
|
|
||||||
return invalid(format!(
|
|
||||||
"Slot '{}' is not in a child list of the body; a slot stands only in Box.children, \
|
|
||||||
Button.content or Overlay.children",
|
|
||||||
slot.param.name
|
|
||||||
));
|
|
||||||
}
|
|
||||||
None => {
|
|
||||||
self.current = None;
|
|
||||||
self.unbound(&format!("Slot '{}'", slot.param.name));
|
|
||||||
node.clone()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Node::Use(used) => self.expand_use(used, scope, depth, root)?,
|
|
||||||
Node::Box(b) => {
|
|
||||||
let common = self.common(&b.common, scope, root)?;
|
|
||||||
let children = self.children(&b.children, scope, depth + 1)?;
|
|
||||||
Node::Box(BoxNode { common, style: b.style.clone(), paint: b.paint.clone(), role: b.role.clone(), children })
|
|
||||||
}
|
|
||||||
Node::Text(t) => {
|
|
||||||
let common = self.common(&t.common, scope, root)?;
|
|
||||||
let content = self.text(&t.content, scope)?;
|
|
||||||
Node::Text(TextNode { common, content, ..t.clone() })
|
|
||||||
}
|
|
||||||
Node::Image(i) => {
|
|
||||||
let common = self.common(&i.common, scope, root)?;
|
|
||||||
let alt = self.text(&i.alt, scope)?;
|
|
||||||
Node::Image(ImageNode { common, alt, ..i.clone() })
|
|
||||||
}
|
|
||||||
Node::Button(b) => {
|
|
||||||
let common = self.common(&b.common, scope, root)?;
|
|
||||||
let on_activate = self.command(&b.on_activate, scope)?;
|
|
||||||
let enabled = self.boolean(&b.enabled, scope)?;
|
|
||||||
let content = self.children(&b.content, scope, depth + 1)?;
|
|
||||||
Node::Button(ButtonNode { common, content, on_activate, enabled })
|
|
||||||
}
|
|
||||||
Node::Toggle(t) => {
|
|
||||||
let common = self.common(&t.common, scope, root)?;
|
|
||||||
let checked = self.boolean(&t.checked, scope)?;
|
|
||||||
let on_change = self.command(&t.on_change, scope)?;
|
|
||||||
Node::Toggle(ToggleNode { common, checked, on_change })
|
|
||||||
}
|
|
||||||
Node::Slider(s) => {
|
|
||||||
let common = self.common(&s.common, scope, root)?;
|
|
||||||
let value = self.number(&s.value, scope)?;
|
|
||||||
let commit = self.command(&s.commit, scope)?;
|
|
||||||
Node::Slider(SliderNode { common, value, commit, ..s.clone() })
|
|
||||||
}
|
|
||||||
Node::TextInput(t) => {
|
|
||||||
let common = self.common(&t.common, scope, root)?;
|
|
||||||
let placeholder = self.text(&t.placeholder, scope)?;
|
|
||||||
let initial = self.text(&t.initial, scope)?;
|
|
||||||
let submit = self.command(&t.submit, scope)?;
|
|
||||||
Node::TextInput(TextInputNode { common, placeholder, initial, submit, ..t.clone() })
|
|
||||||
}
|
|
||||||
Node::Select(s) => {
|
|
||||||
let common = self.common(&s.common, scope, root)?;
|
|
||||||
let options = match &s.options {
|
|
||||||
OptionList::Literal(_) => s.options.clone(),
|
|
||||||
OptionList::Bound(bound) => OptionList::Bound(BoundOptions {
|
|
||||||
collection: self.collection(&bound.collection, scope)?,
|
|
||||||
value_member: bound.value_member.clone(),
|
|
||||||
label_member: bound.label_member.clone(),
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
let value = self.bind(&s.value);
|
|
||||||
let on_change = self.command(&s.on_change, scope)?;
|
|
||||||
Node::Select(SelectNode { common, options, value, on_change })
|
|
||||||
}
|
|
||||||
Node::Repeat(r) => {
|
|
||||||
let common = self.common(&r.common, scope, root)?;
|
|
||||||
let collection = self.collection(&r.collection, scope)?;
|
|
||||||
let template = std::boxed::Box::new(self.node(&r.template, scope, depth + 1, false)?);
|
|
||||||
Node::Repeat(RepeatNode { common, collection, key_member: r.key_member.clone(), template })
|
|
||||||
}
|
|
||||||
Node::Overlay(o) => {
|
|
||||||
let common = self.common(&o.common, scope, root)?;
|
|
||||||
let anchor = match &o.anchor {
|
|
||||||
Anchor::Viewport => Anchor::Viewport,
|
|
||||||
Anchor::Node(anchor) => Anchor::Node(AnchorNode { node: self.id(&anchor.node, scope) }),
|
|
||||||
};
|
|
||||||
let dismiss = self.command(&o.dismiss, scope)?;
|
|
||||||
let children = self.children(&o.children, scope, depth + 1)?;
|
|
||||||
Node::Overlay(OverlayNode { common, anchor, modal: o.modal, dismiss, children })
|
|
||||||
}
|
|
||||||
Node::Plot(p) => {
|
|
||||||
let common = self.common(&p.common, scope, root)?;
|
|
||||||
Node::Plot(PlotNode { common, series: self.bind(&p.series), ..p.clone() })
|
|
||||||
}
|
|
||||||
Node::Embed(e) => {
|
|
||||||
let common = self.common(&e.common, scope, root)?;
|
|
||||||
Node::Embed(EmbedNode { common, ..e.clone() })
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- compositions -------------------------------------------------------------------
|
|
||||||
|
|
||||||
fn load(&mut self, reference: &CompositionRef) -> Result<CompositionDocument, (Code, String)> {
|
|
||||||
let name = format!("{}.{}.v{}", reference.publisher, reference.name.as_str(), reference.version.get());
|
|
||||||
if reference.publisher == thing_std::PUBLISHER {
|
|
||||||
return thing_std::lookup(reference.name.as_str(), reference.version)
|
|
||||||
.ok_or((Code::UnresolvedUse, format!("no compiled-in composition {name}")));
|
|
||||||
}
|
|
||||||
let address = Address {
|
|
||||||
provider: ProviderId::new(reference.publisher.clone()),
|
|
||||||
schema: SchemaId::new(CompositionDocument::SCHEMA_NAME),
|
|
||||||
key: RecordKey::new(reference.record_key()),
|
|
||||||
};
|
|
||||||
self.reads.insert(address.clone());
|
|
||||||
match self.port.read(&address) {
|
|
||||||
Lookup::Present(entry) => match entry.record {
|
|
||||||
Record::Composition(composition) => Ok(composition),
|
|
||||||
_ => Err((Code::CompositionInvalid, format!("the record at {name} is not a composition"))),
|
|
||||||
},
|
|
||||||
Lookup::Absent => Err((Code::UnresolvedUse, format!("no composition published at {name}"))),
|
|
||||||
Lookup::Refused(refusal) => Err((Code::DecodeRefused, format!("{name}: {}", refusal.detail))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The first thing wrong with the composition against its Use, if anything.
|
|
||||||
fn misfit(reference: &CompositionRef, composition: &CompositionDocument, args: &[Arg]) -> Option<String> {
|
|
||||||
if composition.publisher != reference.publisher
|
|
||||||
|| composition.name != reference.name
|
|
||||||
|| composition.version != reference.version
|
|
||||||
{
|
|
||||||
return Some("the composition record's publisher, name or version differs from the Use's reference".into());
|
|
||||||
}
|
|
||||||
let mut declared: HashMap<&str, &ParamKind> = HashMap::new();
|
|
||||||
for param in &composition.params {
|
|
||||||
if declared.insert(¶m.name, ¶m.kind).is_some() {
|
|
||||||
return Some(format!("the composition declares param '{}' twice", param.name));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let mut given: HashSet<&str> = HashSet::new();
|
|
||||||
for arg in args {
|
|
||||||
if !given.insert(&arg.name) {
|
|
||||||
return Some(format!("argument '{}' is given twice", arg.name));
|
|
||||||
}
|
|
||||||
match declared.get(arg.name.as_str()) {
|
|
||||||
None => return Some(format!("argument '{}' names no param of the composition", arg.name)),
|
|
||||||
Some(kind) if kind_name(kind) != arm_name(&arg.value) => {
|
|
||||||
return Some(format!(
|
|
||||||
"argument '{}' is a {} but the param is a {}",
|
|
||||||
arg.name,
|
|
||||||
arm_name(&arg.value),
|
|
||||||
kind_name(kind)
|
|
||||||
));
|
|
||||||
}
|
|
||||||
Some(_) => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
composition
|
|
||||||
.params
|
|
||||||
.iter()
|
|
||||||
.find(|param| !given.contains(param.name.as_str()))
|
|
||||||
.map(|param| format!("param '{}' has no argument", param.name))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An argument in the caller's scope: the form the body will place.
|
|
||||||
fn arg(&mut self, value: &ArgValue, scope: Option<&Scope>, depth: usize) -> Res<ArgValue> {
|
|
||||||
Ok(match value {
|
|
||||||
ArgValue::Text(_) | ArgValue::Number(_) | ArgValue::Bool(_) => value.clone(),
|
|
||||||
ArgValue::Bind(bind) => ArgValue::Bind(self.bind(bind)),
|
|
||||||
ArgValue::Collection(arg) => {
|
|
||||||
ArgValue::Collection(CollectionArg { source: self.subst_collection(&arg.source, scope)? })
|
|
||||||
}
|
|
||||||
ArgValue::Command(arg) => ArgValue::Command(CommandArg { command: self.subst_command(&arg.command, scope)? }),
|
|
||||||
ArgValue::Slot(arg) => ArgValue::Slot(SlotArg { nodes: self.children(&arg.nodes, scope, depth + 1)? }),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn expand_use(&mut self, used: &UseNode, scope: Option<&Scope>, depth: usize, root: bool) -> Res<Node> {
|
|
||||||
let common = self.common(&used.common, scope, root)?;
|
|
||||||
let here = common.id.clone();
|
|
||||||
let reference = &used.composition;
|
|
||||||
let placeholder = |common: NodeCommon| Node::Use(UseNode { common, composition: reference.clone(), args: vec![] });
|
|
||||||
|
|
||||||
let repeats = self.stack.contains(reference);
|
|
||||||
if repeats || self.stack.len() >= self.limits.max_use_depth {
|
|
||||||
let why = if repeats { "uses itself" } else { "is nested too deep" };
|
|
||||||
self.diag(Code::CompositionCycle, Some(here), format!("the composition {why}"));
|
|
||||||
return Ok(placeholder(common));
|
|
||||||
}
|
|
||||||
let composition = match self.load(reference) {
|
|
||||||
Ok(composition) => composition,
|
|
||||||
Err((code, detail)) => {
|
|
||||||
self.diag(code, Some(here), detail);
|
|
||||||
return Ok(placeholder(common));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if let Some(detail) = Self::misfit(reference, &composition, &used.args) {
|
|
||||||
self.diag(Code::CompositionInvalid, Some(here), detail);
|
|
||||||
return Ok(placeholder(common));
|
|
||||||
}
|
|
||||||
|
|
||||||
let mark = self.diagnostics.len();
|
|
||||||
let mut args = HashMap::new();
|
|
||||||
for arg in &used.args {
|
|
||||||
args.insert(arg.name.clone(), self.arg(&arg.value, scope, depth)?);
|
|
||||||
}
|
|
||||||
let inner = Scope {
|
|
||||||
use_id: here.clone(),
|
|
||||||
root_id: body_id(&composition.body),
|
|
||||||
use_visible: common.visible.clone(),
|
|
||||||
use_a11y: common.a11y_label.clone(),
|
|
||||||
args,
|
|
||||||
};
|
|
||||||
self.stack.push(reference.clone());
|
|
||||||
let expanded = self.node(&composition.body, Some(&inner), depth, true);
|
|
||||||
self.stack.pop();
|
|
||||||
match expanded {
|
|
||||||
Ok(node) => Ok(node),
|
|
||||||
Err(Fault::Invalid(detail)) => {
|
|
||||||
self.diagnostics.truncate(mark);
|
|
||||||
self.diag(Code::CompositionInvalid, Some(here), detail);
|
|
||||||
Ok(placeholder(common))
|
|
||||||
}
|
|
||||||
Err(limit) => Err(limit),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The id of a body root. A Slot has none, and the body fails on it before an id is read.
|
|
||||||
/// A copy of an expanded subtree that grows its own stack. The derived `Clone` of `Node` costs about
|
|
||||||
/// 12 KiB of debug stack per level, so a spliced slot argument up to `STACK_BOUND` levels deep would
|
|
||||||
/// overflow it; each container here recurses through `grow`. An expanded subtree holds no Slot and no
|
|
||||||
/// Use with arguments, so the four containers are the only nodes that hold nodes.
|
|
||||||
fn clone_deep(node: &Node) -> Node {
|
|
||||||
super::grow(|| match node {
|
|
||||||
Node::Box(b) => Node::Box(BoxNode {
|
|
||||||
common: b.common.clone(),
|
|
||||||
style: b.style.clone(),
|
|
||||||
paint: b.paint.clone(),
|
|
||||||
role: b.role.clone(),
|
|
||||||
children: b.children.iter().map(clone_deep).collect(),
|
|
||||||
}),
|
|
||||||
Node::Button(b) => Node::Button(ButtonNode {
|
|
||||||
common: b.common.clone(),
|
|
||||||
content: b.content.iter().map(clone_deep).collect(),
|
|
||||||
on_activate: b.on_activate.clone(),
|
|
||||||
enabled: b.enabled.clone(),
|
|
||||||
}),
|
|
||||||
Node::Overlay(o) => Node::Overlay(OverlayNode {
|
|
||||||
common: o.common.clone(),
|
|
||||||
anchor: o.anchor.clone(),
|
|
||||||
modal: o.modal,
|
|
||||||
dismiss: o.dismiss.clone(),
|
|
||||||
children: o.children.iter().map(clone_deep).collect(),
|
|
||||||
}),
|
|
||||||
Node::Repeat(r) => Node::Repeat(RepeatNode {
|
|
||||||
common: r.common.clone(),
|
|
||||||
collection: r.collection.clone(),
|
|
||||||
key_member: r.key_member.clone(),
|
|
||||||
template: std::boxed::Box::new(clone_deep(&r.template)),
|
|
||||||
}),
|
|
||||||
other => other.clone(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn body_id(node: &Node) -> NodeId {
|
|
||||||
match node {
|
|
||||||
Node::Box(n) => n.common.id.clone(),
|
|
||||||
Node::Text(n) => n.common.id.clone(),
|
|
||||||
Node::Image(n) => n.common.id.clone(),
|
|
||||||
Node::Button(n) => n.common.id.clone(),
|
|
||||||
Node::Toggle(n) => n.common.id.clone(),
|
|
||||||
Node::Slider(n) => n.common.id.clone(),
|
|
||||||
Node::TextInput(n) => n.common.id.clone(),
|
|
||||||
Node::Select(n) => n.common.id.clone(),
|
|
||||||
Node::Repeat(n) => n.common.id.clone(),
|
|
||||||
Node::Overlay(n) => n.common.id.clone(),
|
|
||||||
Node::Plot(n) => n.common.id.clone(),
|
|
||||||
Node::Embed(n) => n.common.id.clone(),
|
|
||||||
Node::Use(n) => n.common.id.clone(),
|
|
||||||
Node::Slot(_) => NodeId::new(""),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,165 +0,0 @@
|
||||||
//! The Resolver: per surface, the highest version offered, the last good tree and the composition
|
|
||||||
//! interests that tree's resolution read. It is handed the changes the frame owner drained and
|
|
||||||
//! never drains itself. Every re-resolve reads the port again; no composition is cached here. The
|
|
||||||
//! interests are held through the shared `Ledger`, so the Binder and the Resolver count one
|
|
||||||
//! subscription per address.
|
|
||||||
|
|
||||||
use std::collections::{HashMap, HashSet};
|
|
||||||
|
|
||||||
use thing_contract::{DatabaseEntry, SurfaceDocument, Version};
|
|
||||||
|
|
||||||
use super::{Limits, ResolvedTree, resolve};
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
use crate::port::{Address, Change, Interest, Ledger, Record, StatePort};
|
|
||||||
|
|
||||||
/// What the Resolver holds of one surface.
|
|
||||||
struct Held {
|
|
||||||
/// The highest version offered, accepted or refused: the only one resolved again.
|
|
||||||
document: SurfaceDocument,
|
|
||||||
/// The last tree a resolve produced for a version above every earlier one.
|
|
||||||
tree: Option<ResolvedTree>,
|
|
||||||
/// The interests of the last resolve, which was of `document`.
|
|
||||||
interests: HashSet<Interest>,
|
|
||||||
/// Versions already reported stale.
|
|
||||||
reported: HashSet<Version>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What one `apply` did: its diagnostics, and each surface key whose displayed tree it replaced
|
|
||||||
/// (`true`) or dropped (`false`), sorted by key. A re-resolve that failed keeps its tree and is
|
|
||||||
/// not listed, so the frame owner never infers a change by comparing trees.
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq)]
|
|
||||||
pub struct Intake {
|
|
||||||
pub diagnostics: Vec<Diagnostic>,
|
|
||||||
pub changed: Vec<(String, bool)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Resolver {
|
|
||||||
limits: Limits,
|
|
||||||
surfaces: HashMap<String, Held>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_surface(address: &Address) -> bool {
|
|
||||||
address.schema.as_str() == SurfaceDocument::SCHEMA_NAME
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Resolver {
|
|
||||||
pub fn new(limits: Limits) -> Self {
|
|
||||||
Self { limits, surfaces: HashMap::new() }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The tree displayed for a surface key: the last good one.
|
|
||||||
pub fn tree(&self, surface_key: &str) -> Option<&ResolvedTree> {
|
|
||||||
self.surfaces.get(surface_key).and_then(|held| held.tree.as_ref())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Drop a surface the consumer no longer shows: its interests are released and its entry goes
|
|
||||||
/// with no tombstone (the consumer leaving is not the provider deleting).
|
|
||||||
pub fn forget(&mut self, surface_key: &str, port: &mut dyn StatePort, ledger: &mut Ledger) {
|
|
||||||
if let Some(held) = self.surfaces.remove(surface_key) {
|
|
||||||
ledger.diff(port, &held.interests, &HashSet::new());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One drained change. A surface offer is judged by the version rule; a change at a
|
|
||||||
/// composition a held surface read resolves that surface again from its held document.
|
|
||||||
pub fn apply(&mut self, change: &Change, port: &mut dyn StatePort, ledger: &mut Ledger) -> Intake {
|
|
||||||
let address = match change {
|
|
||||||
Change::Upsert(entry) => &entry.address,
|
|
||||||
Change::Delete(address) => address,
|
|
||||||
Change::Refused(refusal) => &refusal.address,
|
|
||||||
};
|
|
||||||
if is_surface(address) {
|
|
||||||
return match change {
|
|
||||||
Change::Upsert(entry) => match &entry.record {
|
|
||||||
Record::Surface(document) => self.offer(document, port, ledger),
|
|
||||||
_ => Intake::default(),
|
|
||||||
},
|
|
||||||
Change::Delete(address) => {
|
|
||||||
// A tombstone: the highest version stays so an older one is not taken again,
|
|
||||||
// but the tree and the interests go.
|
|
||||||
let mut changed = Vec::new();
|
|
||||||
if let Some(held) = self.surfaces.get_mut(address.key.as_str()) {
|
|
||||||
if held.tree.take().is_some() {
|
|
||||||
changed.push((address.key.as_str().to_string(), false));
|
|
||||||
}
|
|
||||||
let released = std::mem::take(&mut held.interests);
|
|
||||||
ledger.diff(port, &released, &HashSet::new());
|
|
||||||
}
|
|
||||||
Intake { diagnostics: Vec::new(), changed }
|
|
||||||
}
|
|
||||||
Change::Refused(refusal) => Intake {
|
|
||||||
diagnostics: vec![Diagnostic {
|
|
||||||
code: Code::DecodeRefused,
|
|
||||||
surface: address.key.as_str().to_string(),
|
|
||||||
node: None,
|
|
||||||
detail: refusal.detail.clone(),
|
|
||||||
}],
|
|
||||||
changed: Vec::new(),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
let mut readers: Vec<String> = self
|
|
||||||
.surfaces
|
|
||||||
.iter()
|
|
||||||
.filter(|(_, held)| held.interests.iter().any(|interest| interest.matches(address)))
|
|
||||||
.map(|(key, _)| key.clone())
|
|
||||||
.collect();
|
|
||||||
readers.sort();
|
|
||||||
let mut intake = Intake::default();
|
|
||||||
for key in readers {
|
|
||||||
let document = self.surfaces[&key].document.clone();
|
|
||||||
let (diagnostics, replaced) = self.resolve_held(&key, document, port, ledger);
|
|
||||||
intake.diagnostics.extend(diagnostics);
|
|
||||||
if replaced {
|
|
||||||
intake.changed.push((key, true));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
intake
|
|
||||||
}
|
|
||||||
|
|
||||||
fn offer(&mut self, document: &SurfaceDocument, port: &mut dyn StatePort, ledger: &mut Ledger) -> Intake {
|
|
||||||
let key = document.record_key();
|
|
||||||
if let Some(held) = self.surfaces.get_mut(&key)
|
|
||||||
&& document.version <= held.document.version
|
|
||||||
{
|
|
||||||
// A subscribe replays the current record: the same document again is not news.
|
|
||||||
let diagnostics = if document.version == held.document.version && *document == held.document {
|
|
||||||
Vec::new()
|
|
||||||
} else if held.reported.insert(document.version) {
|
|
||||||
vec![Diagnostic {
|
|
||||||
code: Code::StaleVersionIgnored,
|
|
||||||
surface: key,
|
|
||||||
node: None,
|
|
||||||
detail: "version at or below the held version, which stays".into(),
|
|
||||||
}]
|
|
||||||
} else {
|
|
||||||
Vec::new()
|
|
||||||
};
|
|
||||||
return Intake { diagnostics, changed: Vec::new() };
|
|
||||||
}
|
|
||||||
let (diagnostics, replaced) = self.resolve_held(&key, document.clone(), port, ledger);
|
|
||||||
Intake { diagnostics, changed: if replaced { vec![(key, true)] } else { Vec::new() } }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Resolve `document` as the highest offered for `key`: a tree replaces the held one, no tree
|
|
||||||
/// keeps it. The interests become the reads either way. The flag is whether a tree replaced
|
|
||||||
/// the held one.
|
|
||||||
fn resolve_held(&mut self, key: &str, document: SurfaceDocument, port: &mut dyn StatePort, ledger: &mut Ledger) -> (Vec<Diagnostic>, bool) {
|
|
||||||
let resolution = resolve(&document, &*port, &self.limits);
|
|
||||||
let interests: HashSet<Interest> = resolution.reads.into_iter().map(Interest::Record).collect();
|
|
||||||
let held = self.surfaces.entry(key.to_string()).or_insert_with(|| Held {
|
|
||||||
document: document.clone(),
|
|
||||||
tree: None,
|
|
||||||
interests: HashSet::new(),
|
|
||||||
reported: HashSet::new(),
|
|
||||||
});
|
|
||||||
ledger.diff(port, &held.interests, &interests);
|
|
||||||
held.interests = interests;
|
|
||||||
held.document = document;
|
|
||||||
let replaced = resolution.tree.is_some();
|
|
||||||
if let Some(tree) = resolution.tree {
|
|
||||||
held.tree = Some(tree);
|
|
||||||
}
|
|
||||||
(resolution.diagnostics, replaced)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,111 +0,0 @@
|
||||||
//! Resolve: the pure expansion of a surface document into a tree with no composition left in it.
|
|
||||||
//! This is the only code that reads Thing Script structure (Use, Param, CommandRef, node ids).
|
|
||||||
//! It reads compositions through `StatePort::read` and `thing.std` from a compiled-in table,
|
|
||||||
//! holds no state, subscribes to nothing and never drains; `Resolver` is the stateful half.
|
|
||||||
|
|
||||||
mod expand;
|
|
||||||
mod intake;
|
|
||||||
pub mod std;
|
|
||||||
mod validate;
|
|
||||||
|
|
||||||
use thing_contract::SurfaceDocument;
|
|
||||||
|
|
||||||
pub use intake::{Intake, Resolver};
|
|
||||||
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
use crate::port::{Address, StatePort};
|
|
||||||
|
|
||||||
/// Stack left below which recursion moves to a fresh segment, and the segment's size: the values
|
|
||||||
/// cultcache-rs uses for decode. Every recursion over a tree runs through `grow`, so a tree as deep
|
|
||||||
/// as `STACK_BOUND` resolves on a default thread.
|
|
||||||
const RED_ZONE: usize = 512 * 1024;
|
|
||||||
const SEGMENT: usize = 2 * 1024 * 1024;
|
|
||||||
|
|
||||||
/// Runs one recursive step with room for the next, growing the stack when it is nearly spent.
|
|
||||||
pub(crate) fn grow<R>(step: impl FnOnce() -> R) -> R {
|
|
||||||
stacker::maybe_grow(RED_ZONE, SEGMENT, step)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The bounds of one expansion.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub struct Limits {
|
|
||||||
/// Compositions nested in one another; a Use deeper than this is a placeholder.
|
|
||||||
pub max_use_depth: usize,
|
|
||||||
/// The contract's decode bound; a deeper expanded tree is refused.
|
|
||||||
pub max_tree_depth: usize,
|
|
||||||
/// Nodes in the expanded tree; more is refused.
|
|
||||||
pub max_nodes: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for Limits {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self { max_use_depth: 32, max_tree_depth: 256, max_nodes: 65_536 }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A surface document expanded: no Param of any kind remains, every command is declared, every
|
|
||||||
/// state reference names its provider, node ids are unique, and a Use remains only as a
|
|
||||||
/// placeholder leaf (its arguments emptied) beside a diagnostic. Only `resolve` builds one.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct ResolvedTree {
|
|
||||||
document: SurfaceDocument,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ResolvedTree {
|
|
||||||
pub fn document(&self) -> &SurfaceDocument {
|
|
||||||
&self.document
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What one expansion found. `tree` is `None` when a fault refuses the whole document.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct Resolution {
|
|
||||||
pub tree: Option<ResolvedTree>,
|
|
||||||
/// Expansion faults in expansion pre-order, then the finished tree's faults (duplicate ids, depth)
|
|
||||||
/// in tree pre-order.
|
|
||||||
pub diagnostics: Vec<Diagnostic>,
|
|
||||||
/// Every non-std composition address consulted, whether present, absent or refused, once each, ordered
|
|
||||||
/// by provider, schema and key.
|
|
||||||
pub reads: Vec<Address>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn resolve(document: &SurfaceDocument, port: &dyn StatePort, limits: &Limits) -> Resolution {
|
|
||||||
let mut expander = expand::Expander::new(document, port, limits);
|
|
||||||
let root = match expander.root(&document.root) {
|
|
||||||
Ok(root) => Some(root),
|
|
||||||
Err(expand::Fault::Limit(detail)) => {
|
|
||||||
expander.diag(Code::ExpansionLimit, None, detail);
|
|
||||||
None
|
|
||||||
}
|
|
||||||
Err(expand::Fault::Stack(detail)) => {
|
|
||||||
expander.diag(Code::TooDeepToResolve, None, detail);
|
|
||||||
None
|
|
||||||
}
|
|
||||||
Err(expand::Fault::Invalid(detail)) => {
|
|
||||||
expander.diag(Code::CompositionInvalid, None, detail);
|
|
||||||
None
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let mut diagnostics = ::std::mem::take(&mut expander.diagnostics);
|
|
||||||
let mut reads: Vec<Address> = ::std::mem::take(&mut expander.reads).into_iter().collect();
|
|
||||||
reads.sort_by(|a, b| {
|
|
||||||
let key = |address: &Address| (address.provider.as_str().to_string(), address.schema.as_str().to_string(), address.key.as_str().to_string());
|
|
||||||
key(a).cmp(&key(b))
|
|
||||||
});
|
|
||||||
let tree = root.and_then(|root| {
|
|
||||||
diagnostics.extend(validate::check(&root, &document.commands, limits, &document.record_key()));
|
|
||||||
let refused = diagnostics.iter().any(|diagnostic| diagnostic.code.refuses_document());
|
|
||||||
// Field by field: `..document.clone()` would clone the whole input tree to discard it.
|
|
||||||
(!refused).then(|| ResolvedTree {
|
|
||||||
document: SurfaceDocument {
|
|
||||||
provider_id: document.provider_id.clone(),
|
|
||||||
label: document.label.clone(),
|
|
||||||
version: document.version,
|
|
||||||
title: document.title.clone(),
|
|
||||||
root,
|
|
||||||
commands: document.commands.clone(),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
});
|
|
||||||
Resolution { tree, diagnostics, reads }
|
|
||||||
}
|
|
||||||
|
|
@ -1,95 +0,0 @@
|
||||||
//! `thing.std`: the compositions compiled into core. The port is never asked for this
|
|
||||||
//! publisher, so no provider can shadow one.
|
|
||||||
|
|
||||||
use thing_contract::*;
|
|
||||||
|
|
||||||
/// The publisher whose compositions are compiled in.
|
|
||||||
pub const PUBLISHER: &str = "thing.std";
|
|
||||||
|
|
||||||
/// Every compiled-in composition.
|
|
||||||
pub fn all() -> Vec<CompositionDocument> {
|
|
||||||
vec![stat(), card()]
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn lookup(name: &str, version: Version) -> Option<CompositionDocument> {
|
|
||||||
all().into_iter().find(|composition| composition.name.as_str() == name && composition.version == version)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn segment(name: &str) -> Segment {
|
|
||||||
Segment::new(name).expect("a std name is a segment")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn common(id: &str) -> NodeCommon {
|
|
||||||
NodeCommon { id: NodeId::new(id), visible: BoolSource::Literal(BoolLiteral { value: true }), a11y_label: None }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn text(id: &str, content: TextSource, style_token: &str) -> Node {
|
|
||||||
Node::Text(TextNode {
|
|
||||||
common: common(id),
|
|
||||||
content,
|
|
||||||
style_token: style_token.into(),
|
|
||||||
wrap: true,
|
|
||||||
max_lines: None,
|
|
||||||
selectable: false,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn param(name: &str) -> ParamName {
|
|
||||||
ParamName { name: name.into() }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn column(id: &str, children: Vec<Node>) -> Node {
|
|
||||||
let zero = || Dimension::Px(Scalar { value: 0.0 });
|
|
||||||
let auto = || Dimension::Auto;
|
|
||||||
let size = |width, height| Size2 { width, height };
|
|
||||||
let edges = |all: Dimension| Edges { top: all.clone(), right: all.clone(), bottom: all.clone(), left: all };
|
|
||||||
let style = BoxStyle {
|
|
||||||
display: Display::Flex,
|
|
||||||
direction: Direction::Column,
|
|
||||||
wrap: Wrap::NoWrap,
|
|
||||||
gap: size(zero(), Dimension::Px(Scalar { value: 4.0 })),
|
|
||||||
padding: edges(zero()),
|
|
||||||
margin: edges(zero()),
|
|
||||||
size: size(auto(), Dimension::Content),
|
|
||||||
min_size: size(zero(), zero()),
|
|
||||||
max_size: size(auto(), auto()),
|
|
||||||
position: Position::Relative,
|
|
||||||
inset: edges(auto()),
|
|
||||||
overflow: Overflow::Visible,
|
|
||||||
align_items: ItemAlign::Stretch,
|
|
||||||
align_self: ItemAlign::Auto,
|
|
||||||
align_content: ContentAlign::Start,
|
|
||||||
justify_content: ContentAlign::Start,
|
|
||||||
grow: 0.0,
|
|
||||||
shrink: 1.0,
|
|
||||||
basis: Dimension::Auto,
|
|
||||||
grid_columns: vec![],
|
|
||||||
grid_rows: vec![],
|
|
||||||
};
|
|
||||||
let paint = Paint { background: None, border: None, radius: 0.0 };
|
|
||||||
Node::Box(BoxNode { common: common(id), style, paint, role: Role::Group, children })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn composition(name: &str, params: &[(&str, ParamKind)], body: Node) -> CompositionDocument {
|
|
||||||
CompositionDocument {
|
|
||||||
publisher: PUBLISHER.into(),
|
|
||||||
name: segment(name),
|
|
||||||
version: Version::new(1).expect("version 1"),
|
|
||||||
params: params.iter().map(|(name, kind)| ParamDecl { name: (*name).into(), kind: kind.clone() }).collect(),
|
|
||||||
body,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A label over a bound value.
|
|
||||||
fn stat() -> CompositionDocument {
|
|
||||||
let label = text("stat-label", TextSource::Param(param("label")), "caption");
|
|
||||||
let value = text("stat-value", TextSource::Param(param("value")), "title");
|
|
||||||
composition("stat", &[("label", ParamKind::Text), ("value", ParamKind::Bind)], column("stat-root", vec![label, value]))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A title over the nodes passed for `body`.
|
|
||||||
fn card() -> CompositionDocument {
|
|
||||||
let title = text("card-title", TextSource::Param(param("title")), "title");
|
|
||||||
let slot = Node::Slot(SlotNode { param: param("body") });
|
|
||||||
composition("card", &[("title", ParamKind::Text), ("body", ParamKind::Slot)], column("card-root", vec![title, slot]))
|
|
||||||
}
|
|
||||||
|
|
@ -1,119 +0,0 @@
|
||||||
//! The one pass over the finished tree: ids unique, and the tree within its depth limit (a slot's
|
|
||||||
//! nodes are placed deeper than expand saw them). Commands, Params and Slots are judged where they
|
|
||||||
//! land and the node count is expand's alone (it must stop before it builds a tree it would refuse).
|
|
||||||
|
|
||||||
use std::collections::HashSet;
|
|
||||||
|
|
||||||
use thing_contract::{CommandDecl, Node, NodeId};
|
|
||||||
|
|
||||||
use super::Limits;
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
|
|
||||||
/// The child nodes of a node, in order.
|
|
||||||
fn children(node: &Node) -> &[Node] {
|
|
||||||
match node {
|
|
||||||
Node::Box(b) => &b.children,
|
|
||||||
Node::Button(b) => &b.content,
|
|
||||||
Node::Overlay(o) => &o.children,
|
|
||||||
Node::Repeat(r) => std::slice::from_ref(&*r.template),
|
|
||||||
_ => &[],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn id(node: &Node) -> Option<&NodeId> {
|
|
||||||
match node {
|
|
||||||
Node::Box(n) => Some(&n.common.id),
|
|
||||||
Node::Text(n) => Some(&n.common.id),
|
|
||||||
Node::Image(n) => Some(&n.common.id),
|
|
||||||
Node::Button(n) => Some(&n.common.id),
|
|
||||||
Node::Toggle(n) => Some(&n.common.id),
|
|
||||||
Node::Slider(n) => Some(&n.common.id),
|
|
||||||
Node::TextInput(n) => Some(&n.common.id),
|
|
||||||
Node::Select(n) => Some(&n.common.id),
|
|
||||||
Node::Repeat(n) => Some(&n.common.id),
|
|
||||||
Node::Overlay(n) => Some(&n.common.id),
|
|
||||||
Node::Plot(n) => Some(&n.common.id),
|
|
||||||
Node::Embed(n) => Some(&n.common.id),
|
|
||||||
Node::Use(n) => Some(&n.common.id),
|
|
||||||
Node::Slot(_) => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Nodes in the subtree, the node itself included.
|
|
||||||
pub(super) fn size(node: &Node) -> usize {
|
|
||||||
super::grow(|| 1 + children(node).iter().map(size).sum::<usize>())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Faults of the finished tree, in pre-order: duplicate ids, then depth, then each command capture that is not an input node. A tree deeper than the limit is not walked further.
|
|
||||||
pub(super) fn check(root: &Node, commands: &[CommandDecl], limits: &Limits, surface: &str) -> Vec<Diagnostic> {
|
|
||||||
let mut found = Vec::new();
|
|
||||||
let fault = |code, node: Option<&NodeId>, detail: String| Diagnostic {
|
|
||||||
code,
|
|
||||||
surface: surface.to_string(),
|
|
||||||
node: node.cloned(),
|
|
||||||
detail,
|
|
||||||
};
|
|
||||||
let mut seen: HashSet<&NodeId> = HashSet::new();
|
|
||||||
let mut inputs: HashSet<&NodeId> = HashSet::new();
|
|
||||||
let mut too_deep = false;
|
|
||||||
let mut stack = vec![(root, 1usize)];
|
|
||||||
while let Some((node, depth)) = stack.pop() {
|
|
||||||
if depth > limits.max_tree_depth {
|
|
||||||
too_deep = true;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if let Some(id) = id(node) {
|
|
||||||
if matches!(node, Node::Toggle(_) | Node::Slider(_) | Node::Select(_) | Node::TextInput(_)) {
|
|
||||||
inputs.insert(id);
|
|
||||||
}
|
|
||||||
if !seen.insert(id) {
|
|
||||||
found.push(fault(Code::DuplicateNodeId, Some(id), format!("node id '{}' occurs twice", id.as_str())));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
stack.extend(children(node).iter().rev().map(|child| (child, depth + 1)));
|
|
||||||
}
|
|
||||||
if too_deep {
|
|
||||||
found.push(fault(Code::ExpansionLimit, None, format!("the tree is deeper than {} levels", limits.max_tree_depth)));
|
|
||||||
}
|
|
||||||
for capture in commands.iter().flat_map(|decl| &decl.captures) {
|
|
||||||
if !inputs.contains(capture) {
|
|
||||||
found.push(fault(Code::CaptureUndeclared, Some(capture), format!("capture '{}' is not an input node of the surface", capture.as_str())));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
found
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use thing_testkit::build::{boxed, text};
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
/// Runs `work` with about `left` bytes of stack remaining: the stack is burned first, so a recursion
|
|
||||||
/// that does not grow its own runs out inside it.
|
|
||||||
#[inline(never)]
|
|
||||||
fn with_stack_left(left: usize, work: &mut dyn FnMut()) {
|
|
||||||
if stacker::remaining_stack().expect("the thread's stack limit is known") > left {
|
|
||||||
let burn = [0u8; 4096];
|
|
||||||
std::hint::black_box(&burn);
|
|
||||||
with_stack_left(left, work);
|
|
||||||
std::hint::black_box(&burn);
|
|
||||||
} else {
|
|
||||||
work();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn size_of_a_deep_subtree_grows_its_own_stack() {
|
|
||||||
// expand counts a slot argument with `size` after the argument was expanded, from wherever the
|
|
||||||
// stack stands; a 1,000-level argument must not run it out.
|
|
||||||
let mut deep = text("bottom", "x");
|
|
||||||
for level in 1..1000 {
|
|
||||||
deep = boxed(&format!("level-{level}"), vec![deep]);
|
|
||||||
}
|
|
||||||
let mut counted = 0;
|
|
||||||
with_stack_left(100 * 1024, &mut || counted = size(&deep));
|
|
||||||
assert_eq!(counted, 1000);
|
|
||||||
// Dropping a tree this deep needs the room the test thread has outside `with_stack_left`.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,317 +0,0 @@
|
||||||
//! The Cells text engine: `CellText` is the one constructor of terminal text and `CellMeasure` the
|
|
||||||
//! one `Measure` for Cells. Every width and every break a cell backend advances by is decided
|
|
||||||
//! here, per extended grapheme cluster, and no backend computes either.
|
|
||||||
//!
|
|
||||||
//! Order is sanitize, then segment and measure: the text is cleaned (controls become U+FFFD,
|
|
||||||
//! clusters without width are dropped) until segmenting it again changes nothing, so every width
|
|
||||||
//! recorded is the width of exactly the text a terminal receives.
|
|
||||||
//!
|
|
||||||
//! Breaking is CSS `white-space: pre-wrap` with `overflow-wrap: break-word`: mandatory breaks
|
|
||||||
//! always break, soft breaks are UAX #14 Allowed positions on a cluster boundary, trailing spaces
|
|
||||||
//! at a soft break hang (are not emitted), and an unbreakable segment wider than the line breaks
|
|
||||||
//! between clusters. A line takes at least one cluster, so at width 0 every cluster sits on its
|
|
||||||
//! own line. Text is laid out in logical order; bidi reordering is Pixels-only.
|
|
||||||
|
|
||||||
use unicode_linebreak::{BreakOpportunity, linebreaks};
|
|
||||||
use unicode_segmentation::UnicodeSegmentation;
|
|
||||||
use unicode_width::UnicodeWidthStr;
|
|
||||||
|
|
||||||
use crate::bind::Bound;
|
|
||||||
use crate::layout::{Avail, CELL_PX, CellStyle, Constraint, Leaf, Measure, Run, TextLayout, TextLine, TextRequest};
|
|
||||||
|
|
||||||
/// The tab stop, in columns (CSS `tab-size: 8`).
|
|
||||||
const TAB: u32 = 8;
|
|
||||||
|
|
||||||
/// Terminal text: a string with one width per extended grapheme cluster, free of control
|
|
||||||
/// characters and of zero-width clusters, whose clusters re-segment to themselves. A document
|
|
||||||
/// never writes an escape code into a terminal because no other constructor exists.
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
|
||||||
pub struct CellText {
|
|
||||||
text: String,
|
|
||||||
/// The end byte offset and the width in cells of each cluster, in order.
|
|
||||||
clusters: Vec<(u32, u8)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CellText {
|
|
||||||
/// One line of terminal text. Tabs stop at multiples of 8 columns from the start of `text`;
|
|
||||||
/// every control character, line terminators included, becomes U+FFFD (width 1); a cluster
|
|
||||||
/// without width is dropped.
|
|
||||||
pub fn new(text: &str) -> Self {
|
|
||||||
let (clean, open) = clean(text);
|
|
||||||
emit(&atoms(&clean, &open))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn as_str(&self) -> &str {
|
|
||||||
&self.text
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Each cluster with its width in cells.
|
|
||||||
pub fn clusters(&self) -> impl Iterator<Item = (&str, u8)> {
|
|
||||||
let mut start = 0;
|
|
||||||
self.clusters.iter().map(move |&(end, width)| {
|
|
||||||
let cluster = &self.text[start as usize..end as usize];
|
|
||||||
start = end as usize;
|
|
||||||
(cluster, width)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The width of the line in cells: the sum of its cluster widths.
|
|
||||||
pub fn width(&self) -> u32 {
|
|
||||||
self.clusters.iter().map(|&(_, w)| u32::from(w)).sum()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One kept cluster of a paragraph and whether a soft break may precede it. A tab is an atom of
|
|
||||||
/// its own: its width is decided where it falls in a line.
|
|
||||||
struct Atom<'a> {
|
|
||||||
text: &'a str,
|
|
||||||
width: u8,
|
|
||||||
tab: bool,
|
|
||||||
space: bool,
|
|
||||||
open: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Atom<'_> {
|
|
||||||
/// The columns this atom takes when it starts at `column` of its line.
|
|
||||||
fn cols(&self, column: u32) -> u32 {
|
|
||||||
if self.tab { TAB - column % TAB } else { u32::from(self.width) }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_terminator(c: char) -> bool {
|
|
||||||
matches!(c, '\n' | '\r' | '\u{b}' | '\u{c}' | '\u{85}' | '\u{2028}' | '\u{2029}')
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sanitize, to a fixpoint: every control (a tab excepted) becomes U+FFFD and every cluster
|
|
||||||
/// without width is dropped, and since either can change how the rest segments, the result is
|
|
||||||
/// segmented again until nothing more changes. Returns the text and, by byte offset, where a soft
|
|
||||||
/// break may fall; the opportunity at a dropped cluster rides on the next kept one.
|
|
||||||
fn clean(paragraph: &str) -> (String, Vec<bool>) {
|
|
||||||
let mut open = vec![false; paragraph.len() + 1];
|
|
||||||
for (at, kind) in linebreaks(paragraph) {
|
|
||||||
if kind == BreakOpportunity::Allowed {
|
|
||||||
open[at] = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let mut text = paragraph.to_owned();
|
|
||||||
loop {
|
|
||||||
let mut out = String::with_capacity(text.len());
|
|
||||||
let mut marks = Vec::new();
|
|
||||||
let (mut pending, mut changed) = (false, false);
|
|
||||||
for (start, cluster) in text.grapheme_indices(true) {
|
|
||||||
let here = open[start] || pending;
|
|
||||||
pending = false;
|
|
||||||
let first = cluster.chars().next().expect("a cluster has a scalar");
|
|
||||||
let kept = if cluster == "\t" {
|
|
||||||
cluster
|
|
||||||
} else if first.is_control() || is_terminator(first) {
|
|
||||||
changed = true;
|
|
||||||
"\u{fffd}"
|
|
||||||
} else if cluster.width() == 0 {
|
|
||||||
(pending, changed) = (here, true);
|
|
||||||
continue;
|
|
||||||
} else {
|
|
||||||
cluster
|
|
||||||
};
|
|
||||||
if here {
|
|
||||||
marks.push(out.len());
|
|
||||||
}
|
|
||||||
out.push_str(kept);
|
|
||||||
}
|
|
||||||
if !changed {
|
|
||||||
return (text, open);
|
|
||||||
}
|
|
||||||
open = vec![false; out.len() + 1];
|
|
||||||
for mark in marks {
|
|
||||||
open[mark] = true;
|
|
||||||
}
|
|
||||||
text = out;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The clusters of cleaned text.
|
|
||||||
fn atoms<'a>(text: &'a str, open: &[bool]) -> Vec<Atom<'a>> {
|
|
||||||
let mut out: Vec<Atom> = text
|
|
||||||
.grapheme_indices(true)
|
|
||||||
.map(|(start, cluster)| {
|
|
||||||
let tab = cluster == "\t";
|
|
||||||
Atom { text: cluster, width: if tab { 0 } else { cluster.width().min(255) as u8 }, tab, space: tab || cluster == " ", open: open[start] }
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
if let Some(first) = out.first_mut() {
|
|
||||||
first.open = false;
|
|
||||||
}
|
|
||||||
out
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One line as terminal text: tabs become spaces to the next stop from the line's start, and the
|
|
||||||
/// result is cleaned and segmented once more, so its recorded widths are those of the emitted text.
|
|
||||||
fn emit(line: &[Atom]) -> CellText {
|
|
||||||
let mut text = String::new();
|
|
||||||
let mut column = 0;
|
|
||||||
for atom in line {
|
|
||||||
let cols = atom.cols(column);
|
|
||||||
if atom.tab {
|
|
||||||
text.extend(std::iter::repeat_n(' ', cols as usize));
|
|
||||||
} else {
|
|
||||||
text.push_str(atom.text);
|
|
||||||
}
|
|
||||||
column += cols;
|
|
||||||
}
|
|
||||||
let (text, _) = clean(&text);
|
|
||||||
let mut out = CellText::default();
|
|
||||||
for cluster in text.graphemes(true) {
|
|
||||||
out.text.push_str(cluster);
|
|
||||||
out.clusters.push((out.text.len() as u32, cluster.width().min(255) as u8));
|
|
||||||
}
|
|
||||||
out
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The paragraphs of `text`: the pieces between mandatory breaks, terminators removed. A final
|
|
||||||
/// terminator ends the last line and starts no empty one.
|
|
||||||
fn paragraphs(text: &str) -> Vec<&str> {
|
|
||||||
let mut out = Vec::new();
|
|
||||||
let mut from = 0;
|
|
||||||
for (at, kind) in linebreaks(text) {
|
|
||||||
if kind == BreakOpportunity::Mandatory && at < text.len() {
|
|
||||||
out.push(strip_terminator(&text[from..at]));
|
|
||||||
from = at;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
out.push(strip_terminator(&text[from..]));
|
|
||||||
out
|
|
||||||
}
|
|
||||||
|
|
||||||
fn strip_terminator(piece: &str) -> &str {
|
|
||||||
match piece.graphemes(true).next_back() {
|
|
||||||
Some(last) if last.chars().any(is_terminator) => &piece[..piece.len() - last.len()],
|
|
||||||
_ => piece,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The lines of `text` at `cols` columns. `wrap` off breaks at mandatory breaks only.
|
|
||||||
fn break_lines(text: &str, wrap: bool, max_lines: Option<u32>, cols: u32) -> Vec<CellText> {
|
|
||||||
let cap = max_lines.map_or(usize::MAX, |n| n as usize);
|
|
||||||
let mut lines = Vec::new();
|
|
||||||
for paragraph in paragraphs(text) {
|
|
||||||
let (clean, open) = clean(paragraph);
|
|
||||||
let atoms = atoms(&clean, &open);
|
|
||||||
let mut start = 0;
|
|
||||||
loop {
|
|
||||||
if lines.len() >= cap {
|
|
||||||
return lines;
|
|
||||||
}
|
|
||||||
let end = if wrap { fit(&atoms, start, cols) } else { atoms.len() };
|
|
||||||
let mut line = &atoms[start..end];
|
|
||||||
if end < atoms.len() && line.iter().any(|a| !a.space) {
|
|
||||||
// A soft break: the spaces before it hang.
|
|
||||||
while let Some((last, rest)) = line.split_last() {
|
|
||||||
if !last.space {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
line = rest;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
lines.push(emit(line));
|
|
||||||
if end >= atoms.len() {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
start = end;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
lines
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where the line that starts at `start` ends: the last soft break that fits, else the last
|
|
||||||
/// cluster that fits, else (a cluster wider than the room) just that cluster. Spaces hang: they
|
|
||||||
/// never overflow a line.
|
|
||||||
fn fit(atoms: &[Atom], start: usize, cols: u32) -> usize {
|
|
||||||
let (mut width, mut shown) = (0u32, 0u32);
|
|
||||||
let mut candidate = None;
|
|
||||||
for (i, atom) in atoms.iter().enumerate().skip(start) {
|
|
||||||
if atom.open && i > start {
|
|
||||||
candidate = Some(i);
|
|
||||||
}
|
|
||||||
width += atom.cols(width);
|
|
||||||
if !atom.space {
|
|
||||||
shown = width;
|
|
||||||
if shown > cols && i > start {
|
|
||||||
return candidate.unwrap_or(i);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
atoms.len()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The widest unbreakable segment, trailing spaces excluded.
|
|
||||||
fn longest_segment(text: &str) -> u32 {
|
|
||||||
let mut widest = 0;
|
|
||||||
for paragraph in paragraphs(text) {
|
|
||||||
let (clean, open) = clean(paragraph);
|
|
||||||
let (mut column, mut from, mut shown) = (0, 0, 0);
|
|
||||||
for atom in atoms(&clean, &open) {
|
|
||||||
if atom.open {
|
|
||||||
widest = widest.max(shown - from);
|
|
||||||
(from, shown) = (column, column);
|
|
||||||
}
|
|
||||||
column += atom.cols(column);
|
|
||||||
if !atom.space {
|
|
||||||
shown = column;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
widest = widest.max(shown - from);
|
|
||||||
}
|
|
||||||
widest
|
|
||||||
}
|
|
||||||
|
|
||||||
fn lines_for(text: &str, wrap: bool, max_lines: Option<u32>, room: Avail) -> Vec<CellText> {
|
|
||||||
let cols = match room {
|
|
||||||
// `as` saturates: negative and NaN are 0, huge is u32::MAX.
|
|
||||||
Avail::Definite(w) if wrap => w.floor() as u32,
|
|
||||||
_ => u32::MAX,
|
|
||||||
};
|
|
||||||
break_lines(text, wrap, max_lines, cols)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The shipped Cells engine: text by cluster width and UAX #14, controls at fixed cell sizes.
|
|
||||||
#[derive(Clone, Copy, Debug, Default)]
|
|
||||||
pub struct CellMeasure;
|
|
||||||
|
|
||||||
impl Measure for CellMeasure {
|
|
||||||
fn measure(&mut self, leaf: &Leaf, c: Constraint) -> (f32, f32) {
|
|
||||||
match leaf {
|
|
||||||
Leaf::Text { content, wrap, max_lines, .. } => {
|
|
||||||
let text = match content {
|
|
||||||
Bound::Text(text) => text.as_str(),
|
|
||||||
_ => "",
|
|
||||||
};
|
|
||||||
let room = c.known[0].map(Avail::Definite).unwrap_or(c.available[0]);
|
|
||||||
if *wrap && room == Avail::MinContent {
|
|
||||||
let rows = lines_for(text, true, *max_lines, Avail::MaxContent).len();
|
|
||||||
return (longest_segment(text) as f32, rows as f32);
|
|
||||||
}
|
|
||||||
let lines = lines_for(text, *wrap, *max_lines, room);
|
|
||||||
(lines.iter().map(CellText::width).max().unwrap_or(0) as f32, lines.len() as f32)
|
|
||||||
}
|
|
||||||
Leaf::TextInput { multiline, .. } => (25.0, if *multiline { 3.0 } else { 1.0 }),
|
|
||||||
Leaf::Toggle { .. } => (5.0, 1.0),
|
|
||||||
Leaf::Slider { .. } => (20.0, 1.0),
|
|
||||||
Leaf::Select { .. } => (20.0, 1.0),
|
|
||||||
Leaf::Image { asset, .. } => match asset {
|
|
||||||
Bound::Asset(entry) => ((entry.width.get() as f32 / CELL_PX.0).ceil(), (entry.height.get() as f32 / CELL_PX.1).ceil()),
|
|
||||||
_ => (0.0, 0.0),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn text(&mut self, request: &TextRequest, width: f32) -> TextLayout {
|
|
||||||
let lines = lines_for(request.text, request.wrap, request.max_lines, Avail::Definite(width));
|
|
||||||
TextLayout {
|
|
||||||
lines: lines
|
|
||||||
.into_iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(row, text)| TextLine { y: row as f32, height: 1.0, run: Run::Cells { text, style: CellStyle::default() } })
|
|
||||||
.collect(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
//! Terminal text: what a string is made of in a cell grid. The one owner of every Cells width and
|
|
||||||
//! line break (Pixels text is the shaper's, behind the same `Measure` seam).
|
|
||||||
|
|
||||||
mod cells;
|
|
||||||
|
|
||||||
pub use cells::{CellMeasure, CellText};
|
|
||||||
|
|
@ -1,86 +0,0 @@
|
||||||
//! The theme a frame is drawn with: named colours and named text styles, resolved to literals
|
|
||||||
//! in render so a token never reaches a backend. Where a host's theme comes from is
|
|
||||||
//! `thing2:follow_up:theme-record-contract`; render takes a `&Theme`.
|
|
||||||
|
|
||||||
use std::collections::BTreeMap;
|
|
||||||
|
|
||||||
use thing_contract::{ColorRef, Rgba};
|
|
||||||
|
|
||||||
use crate::layout::CellStyle;
|
|
||||||
|
|
||||||
/// What a text style token draws as: the colour render emits, and the size and cell attributes
|
|
||||||
/// the text engine reads when it shapes the line.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct TextStyle {
|
|
||||||
pub color: Rgba,
|
|
||||||
pub size: f32,
|
|
||||||
pub cells: CellStyle,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct Theme {
|
|
||||||
pub colors: BTreeMap<String, Rgba>,
|
|
||||||
pub text: BTreeMap<String, TextStyle>,
|
|
||||||
/// Scrollbar thickness, logical px (one cell in Cells).
|
|
||||||
pub scrollbar: f32,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The colour a token the theme does not hold draws as, so the fault is visible.
|
|
||||||
pub fn fallback() -> Rgba {
|
|
||||||
Rgba { r: 0xff, g: 0x00, b: 0xff, a: 0xff }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn rgba(hex: u32) -> Rgba {
|
|
||||||
Rgba { r: (hex >> 24) as u8, g: (hex >> 16) as u8, b: (hex >> 8) as u8, a: hex as u8 }
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Theme {
|
|
||||||
/// `thing.std`'s default: every token render and the fixtures use.
|
|
||||||
pub fn std() -> Self {
|
|
||||||
let colors = [
|
|
||||||
("thing.surface", 0x1e1e2eff),
|
|
||||||
("thing.error", 0xe5484dff),
|
|
||||||
("thing.placeholder", 0x6e6e80ff),
|
|
||||||
("thing.scrim", 0x00000099),
|
|
||||||
("thing.scrollbar.thumb", 0xffffff66),
|
|
||||||
("thing.control.fill", 0x2c2c3eff),
|
|
||||||
("thing.control.border", 0x4a4a60ff),
|
|
||||||
("thing.control.accent", 0x7c9cffff),
|
|
||||||
("thing.control.text", 0xeeeef4ff),
|
|
||||||
("thing.control.disabled", 0x3a3a48ff),
|
|
||||||
("thing.plot.mark", 0x7c9cffff),
|
|
||||||
]
|
|
||||||
.into_iter()
|
|
||||||
.map(|(name, hex)| (name.to_string(), rgba(hex)))
|
|
||||||
.collect();
|
|
||||||
let style = |hex: u32, size: f32, bold: bool| TextStyle {
|
|
||||||
color: rgba(hex),
|
|
||||||
size,
|
|
||||||
cells: CellStyle { bold, ..CellStyle::default() },
|
|
||||||
};
|
|
||||||
let text = [
|
|
||||||
("title", style(0xffffffff, 24.0, true)),
|
|
||||||
("body", style(0xeeeef4ff, 16.0, false)),
|
|
||||||
("thing.text", style(0xeeeef4ff, 16.0, false)),
|
|
||||||
("thing.text.placeholder", style(0x6e6e80ff, 16.0, false)),
|
|
||||||
]
|
|
||||||
.into_iter()
|
|
||||||
.map(|(name, style)| (name.to_string(), style))
|
|
||||||
.collect();
|
|
||||||
Self { colors, text, scrollbar: 6.0 }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The literal a colour is: a token the theme holds, or the literal itself. `None` is an
|
|
||||||
/// unknown token.
|
|
||||||
pub fn resolve(&self, color: &ColorRef) -> Option<Rgba> {
|
|
||||||
match color {
|
|
||||||
ColorRef::Rgba(literal) => Some(literal.clone()),
|
|
||||||
ColorRef::Token(token) => self.colors.get(&token.name).cloned(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A named colour of the theme's own (render's scrim, error and thumb).
|
|
||||||
pub fn color(&self, name: &str) -> Option<Rgba> {
|
|
||||||
self.colors.get(name).cloned()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,36 +0,0 @@
|
||||||
//! Wall time as core is told it: the host reads its clock and hands core the reading.
|
|
||||||
|
|
||||||
/// Unix milliseconds, UTC.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
||||||
pub struct Timestamp(pub i64);
|
|
||||||
|
|
||||||
impl Timestamp {
|
|
||||||
/// This instant plus `ms` milliseconds, saturating.
|
|
||||||
pub fn plus_ms(self, ms: u32) -> Timestamp {
|
|
||||||
Timestamp(self.0.saturating_add(i64::from(ms)))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// RFC 3339 in UTC to whole seconds (an instant inside a second is floored), as
|
|
||||||
/// `2026-01-01T00:00:00Z`. The civil date comes from days since 1970-01-01 by Hinnant's
|
|
||||||
/// `civil_from_days`, valid for every date this type holds in the proleptic Gregorian calendar.
|
|
||||||
pub fn rfc3339(self) -> String {
|
|
||||||
let seconds = self.0.div_euclid(1000);
|
|
||||||
let days = seconds.div_euclid(86_400);
|
|
||||||
let in_day = seconds.rem_euclid(86_400);
|
|
||||||
let z = days + 719_468;
|
|
||||||
let era = z.div_euclid(146_097);
|
|
||||||
let day_of_era = z.rem_euclid(146_097);
|
|
||||||
let year_of_era = (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
|
|
||||||
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
|
|
||||||
let shifted_month = (5 * day_of_year + 2) / 153;
|
|
||||||
let day = day_of_year - (153 * shifted_month + 2) / 5 + 1;
|
|
||||||
let month = if shifted_month < 10 { shifted_month + 3 } else { shifted_month - 9 };
|
|
||||||
let year = year_of_era + era * 400 + i64::from(month <= 2);
|
|
||||||
format!(
|
|
||||||
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
|
|
||||||
in_day / 3600,
|
|
||||||
in_day % 3600 / 60,
|
|
||||||
in_day % 60
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,260 +0,0 @@
|
||||||
//! The Cells text engine: pinned widths, sanitizing, wrapping, and that `measure` and `text`
|
|
||||||
//! agree. Vectors were checked against unicode-width 0.2.3 (ambiguous width narrow).
|
|
||||||
|
|
||||||
use thing_contract::{AssetEntry, NodeId};
|
|
||||||
use thing_core::bind::Bound;
|
|
||||||
use thing_core::layout::{Avail, Constraint, Leaf, Measure, Run, TextRequest};
|
|
||||||
use thing_core::text::{CellMeasure, CellText};
|
|
||||||
use thing_testkit::build::count;
|
|
||||||
|
|
||||||
fn widths(s: &str) -> Vec<u8> {
|
|
||||||
CellText::new(s).clusters().map(|(_, w)| w).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn width_vectors() {
|
|
||||||
let vectors: &[(&str, &[u8])] = &[
|
|
||||||
("a", &[1]),
|
|
||||||
("\u{4e2d}", &[2]),
|
|
||||||
("\u{ff21}", &[2]),
|
|
||||||
("\u{d55c}", &[2]),
|
|
||||||
("e\u{301}", &[1]),
|
|
||||||
("\u{b1}", &[1]),
|
|
||||||
("\u{3b1}", &[1]),
|
|
||||||
("\u{1f600}", &[2]),
|
|
||||||
("\u{2764}", &[1]),
|
|
||||||
("\u{2764}\u{fe0f}", &[2]),
|
|
||||||
("\u{263a}\u{fe0e}", &[1]),
|
|
||||||
("\u{1f44d}\u{1f3fd}", &[2]),
|
|
||||||
("\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}", &[2]),
|
|
||||||
("\u{1f1ef}\u{1f1f5}", &[2]),
|
|
||||||
("\u{1f1ef}", &[1]),
|
|
||||||
("1\u{fe0f}\u{20e3}", &[2]),
|
|
||||||
("\u{1f3f3}\u{fe0f}\u{200d}\u{1f308}", &[2]),
|
|
||||||
("\u{1100}\u{1161}\u{11a8}", &[2]),
|
|
||||||
("\u{915}\u{94d}\u{937}", &[2]),
|
|
||||||
("\u{e01}\u{e33}", &[2]),
|
|
||||||
("\u{17d8}", &[3]),
|
|
||||||
("\u{a0}", &[1]),
|
|
||||||
("\u{644}\u{627}", &[1, 1]),
|
|
||||||
];
|
|
||||||
for (text, expected) in vectors {
|
|
||||||
assert_eq!(&widths(text), expected, "{text:?}");
|
|
||||||
assert_eq!(CellText::new(text).width(), expected.iter().map(|&w| u32::from(w)).sum::<u32>(), "{text:?} line width is the cluster sum");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn sanitizing() {
|
|
||||||
for c in ['\u{1b}', '\u{7f}', '\u{9b}'] {
|
|
||||||
let s = c.to_string();
|
|
||||||
assert_eq!((CellText::new(&s).as_str(), widths(&s)), ("\u{fffd}", vec![1]), "{c:?}");
|
|
||||||
}
|
|
||||||
assert_eq!(CellText::new("a\tb").as_str(), "a b");
|
|
||||||
assert_eq!(CellText::new("abcdefgh\ti").as_str(), "abcdefgh i");
|
|
||||||
for vanishing in ["\u{202e}", "\u{200b}", "\u{ad}", "\u{200d}", "\u{301}"] {
|
|
||||||
assert_eq!(CellText::new(vanishing).as_str(), "", "{vanishing:?}");
|
|
||||||
}
|
|
||||||
assert_eq!(CellText::new("\u{301}a").as_str(), "a");
|
|
||||||
assert_eq!(CellText::new("x\u{200b}y").as_str(), "xy");
|
|
||||||
// The break opportunity of a dropped cluster survives.
|
|
||||||
assert_eq!(lines("x\u{200b}y", 1), ["x", "y"]);
|
|
||||||
// A terminator handed straight to `new` is a control like any other.
|
|
||||||
assert_eq!(CellText::new("a\nb").as_str(), "a\u{fffd}b");
|
|
||||||
assert_eq!(CellText::new("a\u{2028}b").as_str(), "a\u{fffd}b");
|
|
||||||
assert_eq!(widths("a\u{2028}b"), [1, 1, 1]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn dropping_a_cluster_is_measured_after_the_drop() {
|
|
||||||
// woman, a dropped bidi control, skin tone: the terminal sees one 2-wide cluster.
|
|
||||||
let t = CellText::new("\u{1f469}\u{202c}\u{1f3fd}");
|
|
||||||
assert_eq!(t.as_str(), "\u{1f469}\u{1f3fd}");
|
|
||||||
assert_eq!(t.clusters().map(|(_, w)| w).collect::<Vec<_>>(), [2]);
|
|
||||||
// A control turned U+FFFD leaves the mark after it orphaned, and an orphan is dropped.
|
|
||||||
assert_eq!(CellText::new("\u{1b}\u{301}").as_str(), "\u{fffd}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn tabs_stop_at_eight_from_the_start_of_the_line() {
|
|
||||||
assert_eq!(CellText::new("\t").as_str(), " ".repeat(8));
|
|
||||||
assert_eq!(CellText::new("\t\t").as_str(), " ".repeat(16));
|
|
||||||
assert_eq!(CellText::new("abcdefgh\t").as_str(), format!("abcdefgh{}", " ".repeat(8)));
|
|
||||||
assert_eq!(CellText::new("abc\t\td").as_str(), format!("abc{}d", " ".repeat(13)));
|
|
||||||
assert_eq!(CellText::new("\u{4e2d}\tx").as_str(), format!("\u{4e2d}{}x", " ".repeat(6)));
|
|
||||||
// After a soft break the stop counts from the wrapped line, not the paragraph.
|
|
||||||
assert_eq!(lines("aaaaaaaa bb\tc", 9), ["aaaaaaaa", "bb c"]);
|
|
||||||
// A tab is a space: it hangs at a soft break.
|
|
||||||
assert_eq!(lines("abcdef\tgh", 7), ["abcdef", "gh"]);
|
|
||||||
assert_eq!(lines("ab cd", 9), ["ab", "cd"]);
|
|
||||||
assert_eq!(lines("ab cd", 10), ["ab cd"]);
|
|
||||||
assert_eq!(leaf_measure("a b", true, None, Avail::MinContent).0, 1.0);
|
|
||||||
assert_eq!(leaf_measure("a b", false, None, Avail::MaxContent).0, 9.0);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn width_zero_is_one_cluster_per_line() {
|
|
||||||
assert_eq!(lines("abc", 0), ["a", "b", "c"]);
|
|
||||||
assert_eq!(lines("a b", 0), ["a", "b"]);
|
|
||||||
assert_eq!(lines("\u{4e2d}x", 0), ["\u{4e2d}", "x"]);
|
|
||||||
assert_eq!(lines(" a", 2), [" ", "a"]);
|
|
||||||
assert_eq!(layout_lines("abc", true, None, -3.0), ["a", "b", "c"]);
|
|
||||||
assert_eq!(layout_lines("abc", true, None, f32::NAN), ["a", "b", "c"]);
|
|
||||||
assert_eq!(leaf_measure("abc", true, None, Avail::Definite(0.0)), (1.0, 3.0));
|
|
||||||
assert!(lines("abc def", 0).iter().all(|l| !l.is_empty()));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn every_scalar_is_clean() {
|
|
||||||
for c in (0..=char::MAX as u32).filter_map(char::from_u32) {
|
|
||||||
let t = CellText::new(&c.to_string());
|
|
||||||
assert!(!t.as_str().chars().any(|c| c.is_control()), "{:#x}", c as u32);
|
|
||||||
assert!(t.clusters().all(|(_, w)| (1..=3).contains(&w)), "{:#x}", c as u32);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn leaf_measure(text: &str, wrap: bool, max_lines: Option<u32>, room: Avail) -> (f32, f32) {
|
|
||||||
let node = NodeId::new("n");
|
|
||||||
let content = Bound::Text(text.to_string());
|
|
||||||
let leaf = Leaf::Text { node: &node, content: &content, style_token: "body", wrap, max_lines };
|
|
||||||
CellMeasure.measure(&leaf, Constraint { known: [None, None], available: [room, Avail::MaxContent] })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn layout_lines(text: &str, wrap: bool, max_lines: Option<u32>, width: f32) -> Vec<String> {
|
|
||||||
let node = NodeId::new("n");
|
|
||||||
let request = TextRequest { node: &node, text, style_token: "body", wrap, max_lines };
|
|
||||||
CellMeasure
|
|
||||||
.text(&request, width)
|
|
||||||
.lines
|
|
||||||
.into_iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(row, line)| {
|
|
||||||
assert_eq!((line.y, line.height), (row as f32, 1.0));
|
|
||||||
match line.run {
|
|
||||||
Run::Cells { text, .. } => text.as_str().to_string(),
|
|
||||||
other => panic!("{other:?}"),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn lines(text: &str, width: u32) -> Vec<String> {
|
|
||||||
layout_lines(text, true, None, width as f32)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn wrap_table() {
|
|
||||||
assert_eq!(lines("hello world", 5), ["hello", "world"]);
|
|
||||||
assert_eq!(lines("hello world", 11), ["hello world"]);
|
|
||||||
let han = "\u{4e2d}\u{6587}\u{6587}\u{5b57}";
|
|
||||||
assert_eq!(lines(han, 5), ["\u{4e2d}\u{6587}", "\u{6587}\u{5b57}"]);
|
|
||||||
assert_eq!(lines(han, 3).len(), 4);
|
|
||||||
assert_eq!(lines("\u{4e2d}", 1), ["\u{4e2d}"]);
|
|
||||||
assert_eq!(leaf_measure("\u{4e2d}", true, None, Avail::Definite(1.0)), (2.0, 1.0));
|
|
||||||
assert_eq!(lines("abcdefgh", 3), ["abc", "def", "gh"]);
|
|
||||||
assert_eq!(layout_lines("a\nb", false, None, 80.0), ["a", "b"]);
|
|
||||||
assert_eq!(layout_lines("a\r\nb\u{2028}c", true, None, 80.0), ["a", "b", "c"]);
|
|
||||||
assert_eq!(layout_lines("a\nb", true, Some(1), 80.0), ["a"]);
|
|
||||||
assert_eq!(lines("hello world", 5), ["hello", "world"]);
|
|
||||||
assert_eq!(lines("", 5), [""]);
|
|
||||||
assert_eq!(lines("a\n\nb", 5), ["a", "", "b"]);
|
|
||||||
assert_eq!(lines("a\n", 5), ["a"]);
|
|
||||||
// A break opportunity that falls before a dropped mark (LRM here) is kept for the next cluster.
|
|
||||||
assert_eq!(lines("a \u{200e}bcd", 3), ["a", "bcd"]);
|
|
||||||
// A cluster never splits, however narrow the room.
|
|
||||||
assert_eq!(lines("\u{1f468}\u{200d}\u{1f469}", 1), ["\u{1f468}\u{200d}\u{1f469}"]);
|
|
||||||
assert_eq!(lines("e\u{301}e\u{301}", 1), ["e\u{301}", "e\u{301}"]);
|
|
||||||
assert_eq!(leaf_measure("hello world", true, None, Avail::MinContent).0, 5.0);
|
|
||||||
assert_eq!(leaf_measure("a\nbcd", true, None, Avail::MaxContent).0, 3.0);
|
|
||||||
assert_eq!(leaf_measure("a\nbcd", false, None, Avail::MinContent), (3.0, 2.0));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn measure_agrees_with_text() {
|
|
||||||
let rows: &[(&str, bool, Option<u32>, u32)] = &[
|
|
||||||
("hello world", true, None, 5),
|
|
||||||
("hello world", true, None, 11),
|
|
||||||
("\u{4e2d}\u{6587}\u{6587}\u{5b57}", true, None, 5),
|
|
||||||
("\u{4e2d}\u{6587}\u{6587}\u{5b57}", true, None, 3),
|
|
||||||
("\u{4e2d}", true, None, 1),
|
|
||||||
("abcdefgh", true, None, 3),
|
|
||||||
("a\nb", false, None, 80),
|
|
||||||
("a\nb", true, Some(1), 80),
|
|
||||||
("one two three\tfour five", true, Some(3), 7),
|
|
||||||
("\u{1f469}\u{200d}\u{1f469} x \u{1f600}\u{1f600}\u{1f600}", true, None, 4),
|
|
||||||
("", true, None, 4),
|
|
||||||
];
|
|
||||||
for &(text, wrap, max_lines, width) in rows {
|
|
||||||
let laid = layout_lines(text, wrap, max_lines, width as f32);
|
|
||||||
let (w, h) = leaf_measure(text, wrap, max_lines, Avail::Definite(width as f32));
|
|
||||||
let widest = laid.iter().map(|l| CellText::new(l).width()).max().unwrap_or(0);
|
|
||||||
assert_eq!((w, h), (widest as f32, laid.len() as f32), "{text:?} at {width}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn controls_have_shipped_sizes() {
|
|
||||||
let node = NodeId::new("n");
|
|
||||||
let text = Bound::Text(String::new());
|
|
||||||
let c = Constraint { known: [None, None], available: [Avail::MaxContent, Avail::MaxContent] };
|
|
||||||
let mut m = CellMeasure;
|
|
||||||
assert_eq!(m.measure(&Leaf::TextInput { node: &node, multiline: false, placeholder: &text, value: &text }, c), (25.0, 1.0));
|
|
||||||
assert_eq!(m.measure(&Leaf::TextInput { node: &node, multiline: true, placeholder: &text, value: &text }, c), (25.0, 3.0));
|
|
||||||
assert_eq!(m.measure(&Leaf::Toggle { node: &node }, c), (5.0, 1.0));
|
|
||||||
assert_eq!(m.measure(&Leaf::Slider { node: &node }, c), (20.0, 1.0));
|
|
||||||
assert_eq!(m.measure(&Leaf::Select { node: &node, selected: &text }, c), (20.0, 1.0));
|
|
||||||
assert_eq!(m.measure(&Leaf::Image { node: &node, asset: &Bound::Absent }, c), (0.0, 0.0));
|
|
||||||
let entry = AssetEntry { id: "a".into(), media_type: "image/png".into(), uri: "asset://a".into(), width: count(17), height: count(33) };
|
|
||||||
assert_eq!(m.measure(&Leaf::Image { node: &node, asset: &Bound::Asset(entry) }, c), (3.0, 3.0), "extent over (8, 16), rounded up");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Random strings, every control among them, never panic and never put a control character into
|
|
||||||
/// any line at any width.
|
|
||||||
#[test]
|
|
||||||
fn fuzz_never_emits_a_control() {
|
|
||||||
let mut seed = 0x9e37_79b9_7f4a_7c15_u64;
|
|
||||||
let mut next = move || {
|
|
||||||
seed ^= seed << 13;
|
|
||||||
seed ^= seed >> 7;
|
|
||||||
seed ^= seed << 17;
|
|
||||||
seed
|
|
||||||
};
|
|
||||||
let pool: Vec<char> = (0u32..0x20)
|
|
||||||
.chain(0x7f..0xa0)
|
|
||||||
.chain([0x2028, 0x2029, 0x200b, 0x200d, 0xfe0f, 0x301, 0x20, 0x9, 0x4e2d, 0x1f600, 0x1f469, 0x1f3fd, 0x202c, 0x1f1ef, 0x1f1f5, 0x600, 0x20e3])
|
|
||||||
.filter_map(char::from_u32)
|
|
||||||
.collect();
|
|
||||||
for round in 0..400_000 {
|
|
||||||
let text: String = if round % 4 == 0 {
|
|
||||||
// Raw bytes, so truncated and surrogate encodings become U+FFFD.
|
|
||||||
let bytes: Vec<u8> = (0..(next() % 40)).map(|_| next() as u8).collect();
|
|
||||||
String::from_utf8_lossy(&bytes).into_owned()
|
|
||||||
} else {
|
|
||||||
(0..(next() % 40))
|
|
||||||
.map(|_| match next() % 3 {
|
|
||||||
0 => pool[(next() % pool.len() as u64) as usize],
|
|
||||||
1 => char::from_u32((next() % 0x30000) as u32).unwrap_or('\u{fffd}'),
|
|
||||||
_ => char::from(b'a' + (next() % 26) as u8),
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
};
|
|
||||||
let width = (next() % 12) as f32;
|
|
||||||
let wrap = next() % 2 == 0;
|
|
||||||
for line in layout_lines(&text, wrap, None, width) {
|
|
||||||
assert!(!line.chars().any(|c| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}')), "{text:?} -> {line:?}");
|
|
||||||
}
|
|
||||||
// What is emitted measures to what was recorded: measuring it again changes nothing.
|
|
||||||
let node = NodeId::new("n");
|
|
||||||
let request = TextRequest { node: &node, text: &text, style_token: "body", wrap, max_lines: None };
|
|
||||||
for line in CellMeasure.text(&request, width).lines {
|
|
||||||
let Run::Cells { text: emitted, .. } = line.run else { panic!() };
|
|
||||||
assert_eq!(CellText::new(emitted.as_str()), emitted, "{text:?} at {width}");
|
|
||||||
assert!(emitted.clusters().all(|(_, w)| w >= 1));
|
|
||||||
}
|
|
||||||
let lone = CellText::new(&text);
|
|
||||||
assert_eq!(CellText::new(lone.as_str()), lone, "{text:?}");
|
|
||||||
let _ = leaf_measure(&text, wrap, Some(3), Avail::Definite(width));
|
|
||||||
let _ = leaf_measure(&text, wrap, None, Avail::MinContent);
|
|
||||||
assert!(!CellText::new(&text).as_str().chars().any(|c| c.is_control()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,492 +0,0 @@
|
||||||
//! The frame entry: Core::frame equals the stages composed by hand, and keeps its promises
|
|
||||||
//! about the port, the last good frame and the room it is given.
|
|
||||||
|
|
||||||
use thing_contract::*;
|
|
||||||
use thing_core::bind::Binder;
|
|
||||||
use thing_core::diagnostic::Code;
|
|
||||||
use thing_core::input::{InputEvent, Key, Modifiers, PointerButton, WheelUnit};
|
|
||||||
use thing_core::layout::{LayoutFrame, Metrics, layout};
|
|
||||||
use thing_core::port::{Address, Ledger};
|
|
||||||
use thing_core::render::{RenderCommand, RenderInput, ScrollOffsets, Session, render};
|
|
||||||
use thing_core::resolve::{Limits, resolve};
|
|
||||||
use thing_core::theme::Theme;
|
|
||||||
use thing_core::time::Timestamp;
|
|
||||||
use thing_core::{Config, Core, FrameInput, FrameOutput, Ports};
|
|
||||||
use thing_testkit::build::*;
|
|
||||||
use thing_testkit::fixture::Fixture;
|
|
||||||
use thing_testkit::ids::SeqIds;
|
|
||||||
use thing_testkit::measure::FixedMeasure;
|
|
||||||
use thing_testkit::mem_state::{Call, MemState};
|
|
||||||
use thing_testkit::state::{self, Swarm};
|
|
||||||
|
|
||||||
const PROVIDER: &str = "provider.frame";
|
|
||||||
|
|
||||||
fn measure(metrics: Metrics) -> FixedMeasure {
|
|
||||||
match metrics {
|
|
||||||
Metrics::Pixels => FixedMeasure::pixels(),
|
|
||||||
Metrics::Cells => FixedMeasure::cells(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn fresh(metrics: Metrics) -> Core {
|
|
||||||
Core::new(Config::new(metrics, "renderer.test"), Box::new(measure(metrics)))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn input(viewport: (f32, f32), scale: f32) -> FrameInput {
|
|
||||||
FrameInput { now: Timestamp(0), viewport, scale, events: vec![] }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn run(core: &mut Core, state: &mut MemState, input: FrameInput) -> FrameOutput {
|
|
||||||
core.frame(input, Ports { state, ids: &mut SeqIds::new() })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn show(core: &mut Core, document: &SurfaceDocument) {
|
|
||||||
core.show(document.provider_id.clone(), RecordKey::new(document.record_key()));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn world(fixture: Fixture) -> MemState {
|
|
||||||
let mut state = MemState::from_fixture(fixture);
|
|
||||||
state::script(fixture, &mut state);
|
|
||||||
state
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The commands of the stages composed by hand, as tests/render.rs composes them.
|
|
||||||
fn staged(document: &SurfaceDocument, state: &mut MemState, viewport: (f32, f32), scale: f32, metrics: Metrics) -> Vec<RenderCommand> {
|
|
||||||
let limits = Limits::default();
|
|
||||||
let tree = resolve(document, state, &limits).tree.expect("resolves");
|
|
||||||
let mut binder = Binder::new(limits);
|
|
||||||
binder.bind(tree, state, &mut Ledger::new());
|
|
||||||
let bound = binder.tree(&document.record_key()).expect("bound");
|
|
||||||
let frame = LayoutFrame { viewport, scale, metrics };
|
|
||||||
let laid = layout(bound, &frame, &mut measure(metrics)).unwrap();
|
|
||||||
let scroll = ScrollOffsets::default();
|
|
||||||
let theme = Theme::std();
|
|
||||||
let input = RenderInput { scale, metrics, viewport, scroll: &scroll, theme: &theme, session: Session::EMPTY };
|
|
||||||
render(bound, &laid, &input, &mut measure(metrics)).commands
|
|
||||||
}
|
|
||||||
|
|
||||||
fn inline(version: i64, root: Node) -> SurfaceDocument {
|
|
||||||
SurfaceDocument {
|
|
||||||
provider_id: ProviderId::new(PROVIDER),
|
|
||||||
label: seg("main"),
|
|
||||||
version: ver(version),
|
|
||||||
title: "frame".into(),
|
|
||||||
root,
|
|
||||||
commands: vec![],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn say(version: i64, words: &str) -> SurfaceDocument {
|
|
||||||
inline(version, boxed("root", vec![text("words", words)]))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn surface_address(document: &SurfaceDocument) -> Address {
|
|
||||||
Address {
|
|
||||||
provider: document.provider_id.clone(),
|
|
||||||
schema: SchemaId::new(SurfaceDocument::SCHEMA_NAME),
|
|
||||||
key: RecordKey::new(document.record_key()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn codes(output: &FrameOutput) -> Vec<Code> {
|
|
||||||
output.diagnostics.iter().map(|diagnostic| diagnostic.code).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn count(state: &MemState, wanted: impl Fn(&Call) -> bool) -> usize {
|
|
||||||
state.calls().iter().filter(|call| wanted(call)).count()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn pipeline_equals_the_stages() {
|
|
||||||
let cells = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
|
|
||||||
let mut state = world(Fixture::F01SwarmDashboard);
|
|
||||||
let mut one = fresh(Metrics::Cells);
|
|
||||||
show(&mut one, &cells);
|
|
||||||
let output = run(&mut one, &mut state, input((100.0, 37.0), 1.0));
|
|
||||||
let expected = staged(&cells, &mut world(Fixture::F01SwarmDashboard), (100.0, 37.0), 1.0, Metrics::Cells);
|
|
||||||
assert!(!expected.is_empty());
|
|
||||||
assert_eq!(output.commands, expected);
|
|
||||||
assert_eq!(output.next_wake, None);
|
|
||||||
|
|
||||||
let list = Fixture::F06ScrollList.load().surfaces.remove(0);
|
|
||||||
let mut state = world(Fixture::F06ScrollList);
|
|
||||||
let mut two = fresh(Metrics::Pixels);
|
|
||||||
show(&mut two, &list);
|
|
||||||
let output = run(&mut two, &mut state, input((800.0, 600.0), 1.5));
|
|
||||||
let expected = staged(&list, &mut world(Fixture::F06ScrollList), (800.0, 600.0), 1.5, Metrics::Pixels);
|
|
||||||
assert!(!expected.is_empty());
|
|
||||||
assert_eq!(output.commands, expected);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn an_idle_frame_draws_the_same_and_drains_once() {
|
|
||||||
let document = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
|
|
||||||
let mut state = world(Fixture::F01SwarmDashboard);
|
|
||||||
let mut core = fresh(Metrics::Cells);
|
|
||||||
show(&mut core, &document);
|
|
||||||
let first = run(&mut core, &mut state, input((100.0, 37.0), 1.0));
|
|
||||||
assert_eq!(count(&state, |call| *call == Call::Drain), 1);
|
|
||||||
let before = state.calls().len();
|
|
||||||
let second = run(&mut core, &mut state, input((100.0, 37.0), 1.0));
|
|
||||||
assert_eq!(second.commands, first.commands);
|
|
||||||
assert_eq!(state.calls()[before..], [Call::Drain]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn show_holds_the_interest_before_it_reads_and_draws_when_published() {
|
|
||||||
let document = say(1, "hello");
|
|
||||||
let mut state = MemState::new();
|
|
||||||
let mut core = fresh(Metrics::Cells);
|
|
||||||
show(&mut core, &document);
|
|
||||||
let output = run(&mut core, &mut state, input((40.0, 5.0), 1.0));
|
|
||||||
assert_eq!(output.commands, vec![]);
|
|
||||||
assert_eq!(output.diagnostics, vec![]);
|
|
||||||
let address = surface_address(&document);
|
|
||||||
let calls = state.calls();
|
|
||||||
let subscribe = calls.iter().position(|call| matches!(call, Call::Subscribe(interest) if interest.matches(&address))).expect("subscribed");
|
|
||||||
let read = calls.iter().position(|call| *call == Call::Read(address.clone())).expect("read");
|
|
||||||
assert!(subscribe < read, "{calls:?}");
|
|
||||||
|
|
||||||
state.put(&document.provider_id, &document);
|
|
||||||
let output = run(&mut core, &mut state, input((40.0, 5.0), 1.0));
|
|
||||||
assert_eq!(output.commands, staged(&document, &mut MemState::new(), (40.0, 5.0), 1.0, Metrics::Cells));
|
|
||||||
assert!(!output.commands.is_empty());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_republish_replaces_the_picture_and_a_delete_empties_it() {
|
|
||||||
let v1 = say(1, "first");
|
|
||||||
let v2 = say(2, "second");
|
|
||||||
let mut state = MemState::new();
|
|
||||||
state.put(&v1.provider_id, &v1);
|
|
||||||
let mut core = fresh(Metrics::Cells);
|
|
||||||
show(&mut core, &v1);
|
|
||||||
let at = (40.0, 5.0);
|
|
||||||
let first = run(&mut core, &mut state, input(at, 1.0));
|
|
||||||
assert_eq!(first.commands, staged(&v1, &mut MemState::new(), at, 1.0, Metrics::Cells));
|
|
||||||
|
|
||||||
state.put(&v2.provider_id, &v2);
|
|
||||||
let second = run(&mut core, &mut state, input(at, 1.0));
|
|
||||||
assert_eq!(second.commands, staged(&v2, &mut MemState::new(), at, 1.0, Metrics::Cells));
|
|
||||||
assert_ne!(second.commands, first.commands);
|
|
||||||
assert_eq!(codes(&second), vec![]);
|
|
||||||
|
|
||||||
// The same record delivered again is not news.
|
|
||||||
state.put(&v2.provider_id, &v2);
|
|
||||||
let again = run(&mut core, &mut state, input(at, 1.0));
|
|
||||||
assert_eq!(codes(&again), vec![]);
|
|
||||||
assert_eq!(again.commands, second.commands);
|
|
||||||
|
|
||||||
// A different document at the held version is refused and the held one stays.
|
|
||||||
let other = say(2, "impostor");
|
|
||||||
state.put(&other.provider_id, &other);
|
|
||||||
let stale = run(&mut core, &mut state, input(at, 1.0));
|
|
||||||
assert_eq!(codes(&stale), vec![Code::StaleVersionIgnored]);
|
|
||||||
assert_eq!(stale.commands, second.commands);
|
|
||||||
|
|
||||||
state.delete(&surface_address(&v2));
|
|
||||||
let gone = run(&mut core, &mut state, input(at, 1.0));
|
|
||||||
assert_eq!(gone.commands, vec![]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_changed_state_record_draws_and_a_late_composition_rebinds() {
|
|
||||||
let document = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
|
|
||||||
let mut state = world(Fixture::F01SwarmDashboard);
|
|
||||||
let mut core = fresh(Metrics::Cells);
|
|
||||||
show(&mut core, &document);
|
|
||||||
let at = (100.0, 37.0);
|
|
||||||
let before = run(&mut core, &mut state, input(at, 1.0));
|
|
||||||
|
|
||||||
let summary = Swarm { id: "summary".into(), name: "Swarm".into(), load: 0.93 };
|
|
||||||
state.put_state(&ProviderId::new("provider.swarm"), "summary", &summary);
|
|
||||||
let after = run(&mut core, &mut state, input(at, 1.0));
|
|
||||||
let mut moved = world(Fixture::F01SwarmDashboard);
|
|
||||||
moved.put_state(&ProviderId::new("provider.swarm"), "summary", &summary);
|
|
||||||
assert_eq!(after.commands, staged(&document, &mut moved, at, 1.0, Metrics::Cells));
|
|
||||||
assert_ne!(after.commands, before.commands);
|
|
||||||
|
|
||||||
// f09: the surface is published first and its composition after.
|
|
||||||
let stack = Fixture::F09CompositionStack.load();
|
|
||||||
let surface = stack.surfaces[0].clone();
|
|
||||||
let mut state = MemState::new();
|
|
||||||
state.put(&surface.provider_id, &surface);
|
|
||||||
for (key, record) in state::swarm_records() {
|
|
||||||
state.put_state(&ProviderId::new("provider.stack"), key, &record);
|
|
||||||
}
|
|
||||||
let mut late = fresh(Metrics::Cells);
|
|
||||||
show(&mut late, &surface);
|
|
||||||
let placeholder = run(&mut late, &mut state, input(at, 1.0));
|
|
||||||
assert!(codes(&placeholder).contains(&Code::UnresolvedUse), "{:?}", codes(&placeholder));
|
|
||||||
for composition in &stack.compositions {
|
|
||||||
state.put(&ProviderId::new(composition.publisher.clone()), composition);
|
|
||||||
}
|
|
||||||
let resolved = run(&mut late, &mut state, input(at, 1.0));
|
|
||||||
let mut full = MemState::from_fixture(Fixture::F09CompositionStack);
|
|
||||||
for (key, record) in state::swarm_records() {
|
|
||||||
full.put_state(&ProviderId::new("provider.stack"), key, &record);
|
|
||||||
}
|
|
||||||
assert_eq!(resolved.commands, staged(&surface, &mut full, at, 1.0, Metrics::Cells));
|
|
||||||
assert_ne!(resolved.commands, placeholder.commands);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn no_room_draws_nothing_without_a_diagnostic_and_the_next_frame_draws_again() {
|
|
||||||
let document = say(1, "room");
|
|
||||||
let mut state = MemState::new();
|
|
||||||
state.put(&document.provider_id, &document);
|
|
||||||
let mut core = fresh(Metrics::Cells);
|
|
||||||
show(&mut core, &document);
|
|
||||||
let first = run(&mut core, &mut state, input((40.0, 5.0), 1.0));
|
|
||||||
assert!(!first.commands.is_empty());
|
|
||||||
let cramped = run(&mut core, &mut state, input((0.0, 37.0), 1.0));
|
|
||||||
assert_eq!(cramped.commands, vec![]);
|
|
||||||
assert_eq!(cramped.diagnostics, vec![]);
|
|
||||||
let again = run(&mut core, &mut state, input((40.0, 5.0), 1.0));
|
|
||||||
assert_eq!(again.commands, first.commands);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_layout_past_the_precision_bound_keeps_the_last_good_frame() {
|
|
||||||
let good = say(1, "fits");
|
|
||||||
// Two boxes side by side that together reach past the bound: neither alone is refused.
|
|
||||||
let slab = |id: &str| match boxed(id, vec![]) {
|
|
||||||
Node::Box(mut slab) => {
|
|
||||||
slab.style.size = size2(px(1_500_000.0), px(10.0));
|
|
||||||
Node::Box(slab)
|
|
||||||
}
|
|
||||||
other => other,
|
|
||||||
};
|
|
||||||
let mut wide = inline(2, boxed("root", vec![slab("left"), slab("right")]));
|
|
||||||
if let Node::Box(root) = &mut wide.root {
|
|
||||||
root.style.direction = Direction::Row;
|
|
||||||
}
|
|
||||||
let mut state = MemState::new();
|
|
||||||
state.put(&good.provider_id, &good);
|
|
||||||
let mut core = fresh(Metrics::Pixels);
|
|
||||||
show(&mut core, &good);
|
|
||||||
let first = run(&mut core, &mut state, input((800.0, 600.0), 1.0));
|
|
||||||
assert!(!first.commands.is_empty());
|
|
||||||
state.put(&wide.provider_id, &wide);
|
|
||||||
let refused = run(&mut core, &mut state, input((800.0, 600.0), 1.0));
|
|
||||||
assert_eq!(refused.commands, first.commands);
|
|
||||||
assert_eq!(codes(&refused), vec![Code::LayoutOutOfRange]);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn every_event() -> Vec<InputEvent> {
|
|
||||||
let modifiers = Modifiers { shift: true, ctrl: false, alt: true, meta: false };
|
|
||||||
let at = (3.5, 2.5);
|
|
||||||
vec![
|
|
||||||
InputEvent::Key { key: Key::Char('A'), modifiers, repeat: false },
|
|
||||||
InputEvent::Key { key: Key::F(5), modifiers: Modifiers::default(), repeat: true },
|
|
||||||
InputEvent::Text("hi".into()),
|
|
||||||
InputEvent::Compose { text: "か".into(), cursor: Some((0, 3)) },
|
|
||||||
InputEvent::PointerDown { at, button: PointerButton::Primary, modifiers },
|
|
||||||
InputEvent::PointerMove { at, modifiers },
|
|
||||||
InputEvent::PointerUp { at, button: PointerButton::Primary, modifiers },
|
|
||||||
InputEvent::PointerCancel,
|
|
||||||
InputEvent::Wheel { at, delta: (0.0, 1.0), unit: WheelUnit::Lines, modifiers },
|
|
||||||
InputEvent::Focus(false),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn keys_text_composition_and_focus_change_nothing_yet() {
|
|
||||||
let document = Fixture::F06ScrollList.load().surfaces.remove(0);
|
|
||||||
let at = (800.0, 600.0);
|
|
||||||
let (mut quiet_state, mut busy_state) = (world(Fixture::F06ScrollList), world(Fixture::F06ScrollList));
|
|
||||||
let (mut quiet, mut busy) = (fresh(Metrics::Pixels), fresh(Metrics::Pixels));
|
|
||||||
show(&mut quiet, &document);
|
|
||||||
show(&mut busy, &document);
|
|
||||||
let plain = run(&mut quiet, &mut quiet_state, input(at, 1.0));
|
|
||||||
let mut with_events = input(at, 1.0);
|
|
||||||
// The pointer is routed (tests/input.rs); keys, text, composition and focus are the focus cut's.
|
|
||||||
with_events.events = every_event().into_iter().filter(|event| !matches!(event, InputEvent::PointerDown { .. } | InputEvent::PointerMove { .. } | InputEvent::PointerUp { .. } | InputEvent::PointerCancel | InputEvent::Wheel { .. })).collect();
|
|
||||||
let output = run(&mut busy, &mut busy_state, with_events);
|
|
||||||
assert_eq!(output, plain);
|
|
||||||
assert_eq!(busy_state.calls(), quiet_state.calls());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn showing_another_surface_releases_the_first() {
|
|
||||||
let (a, b) = (say(1, "alpha"), {
|
|
||||||
let mut b = say(1, "beta");
|
|
||||||
b.label = seg("other");
|
|
||||||
b
|
|
||||||
});
|
|
||||||
let mut state = MemState::new();
|
|
||||||
state.put(&a.provider_id, &a);
|
|
||||||
state.put(&b.provider_id, &b);
|
|
||||||
let mut core = fresh(Metrics::Cells);
|
|
||||||
let at = (40.0, 5.0);
|
|
||||||
show(&mut core, &a);
|
|
||||||
let first = run(&mut core, &mut state, input(at, 1.0));
|
|
||||||
assert_eq!(count(&state, |call| matches!(call, Call::Unsubscribe(_))), 0);
|
|
||||||
show(&mut core, &b);
|
|
||||||
let second = run(&mut core, &mut state, input(at, 1.0));
|
|
||||||
assert_eq!(count(&state, |call| matches!(call, Call::Unsubscribe(_))), 1);
|
|
||||||
assert_eq!(second.commands, staged(&b, &mut MemState::new(), at, 1.0, Metrics::Cells));
|
|
||||||
assert_ne!(second.commands, first.commands);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A random box tree: sizes from a hostile list (zero, negative, NaN, past the bound), scroll and
|
|
||||||
/// clip boxes, texts.
|
|
||||||
fn random_node(next: &mut dyn FnMut() -> u64, id: &mut u32, depth: u32) -> Node {
|
|
||||||
let sizes = [0.0, 1.0, 7.5, 40.0, 100.0, 5000.0, 1e6, 1e7, -4.0, f64::NAN];
|
|
||||||
*id += 1;
|
|
||||||
let name = format!("n{id}");
|
|
||||||
if depth == 0 || next() % 4 == 0 {
|
|
||||||
return text(&name, &format!("text {id}"));
|
|
||||||
}
|
|
||||||
let Node::Box(mut node) = boxed(&name, vec![]) else { unreachable!() };
|
|
||||||
node.style.size = size2(px(sizes[(next() % 10) as usize]), px(sizes[(next() % 10) as usize]));
|
|
||||||
node.style.direction = if next() % 2 == 0 { Direction::Row } else { Direction::Column };
|
|
||||||
node.style.overflow = [Overflow::Visible, Overflow::Clip, Overflow::Scroll][(next() % 3) as usize].clone();
|
|
||||||
let children = next() % 4;
|
|
||||||
node.children = (0..children).map(|_| random_node(next, id, depth - 1)).collect();
|
|
||||||
Node::Box(node)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Fixed seeds for reproducibility, plus `THING_FRAME_SEED` when set; a failure names its seed.
|
|
||||||
#[test]
|
|
||||||
fn random_documents_and_inputs_never_panic_and_the_frame_is_deterministic() {
|
|
||||||
let mut seeds = vec![0x9E37_79B9_7F4A_7C15u64, 0xD1B5_4A32_D192_ED03, 0x2545_F491_4F6C_DD1D, 7];
|
|
||||||
if let Some(extra) = std::env::var("THING_FRAME_SEED").ok().and_then(|v| v.parse().ok()) {
|
|
||||||
seeds.push(extra);
|
|
||||||
}
|
|
||||||
for seed in seeds {
|
|
||||||
random_run(seed);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn random_run(mut seed: u64) {
|
|
||||||
let mut next = move || {
|
|
||||||
seed ^= seed << 13;
|
|
||||||
seed ^= seed >> 7;
|
|
||||||
seed ^= seed << 17;
|
|
||||||
seed
|
|
||||||
};
|
|
||||||
let rooms = [(100.0, 37.0), (0.0, 0.0), (-5.0, 10.0), (f32::NAN, 4.0), (f32::INFINITY, 4.0), (800.0, 600.0), (1e9, 1e9), (1.0, 1.0)];
|
|
||||||
let scales = [1.0, 1.5, 0.0, -1.0, f32::NAN, f32::INFINITY, 1e6, 2.0];
|
|
||||||
for metrics in [Metrics::Pixels, Metrics::Cells] {
|
|
||||||
let (mut left, mut right) = (fresh(metrics), fresh(metrics));
|
|
||||||
let (mut left_state, mut right_state) = (MemState::new(), MemState::new());
|
|
||||||
let mut shown = false;
|
|
||||||
for round in 0..200i64 {
|
|
||||||
if next() % 9 != 0 {
|
|
||||||
let mut id = 0;
|
|
||||||
let document = inline(round + 1, random_node(&mut next, &mut id, 4));
|
|
||||||
if !shown {
|
|
||||||
show(&mut left, &document);
|
|
||||||
show(&mut right, &document);
|
|
||||||
shown = true;
|
|
||||||
}
|
|
||||||
left_state.put(&document.provider_id, &document);
|
|
||||||
right_state.put(&document.provider_id, &document);
|
|
||||||
} else if shown {
|
|
||||||
let address = surface_address(&inline(1, boxed("root", vec![])));
|
|
||||||
left_state.delete(&address);
|
|
||||||
right_state.delete(&address);
|
|
||||||
}
|
|
||||||
let room = rooms[(next() % 8) as usize];
|
|
||||||
let scale = scales[(next() % 8) as usize];
|
|
||||||
let events = every_event().into_iter().take((next() % 11) as usize).collect::<Vec<_>>();
|
|
||||||
let frame = FrameInput { now: Timestamp(round), viewport: room, scale, events };
|
|
||||||
let one = run(&mut left, &mut left_state, frame.clone());
|
|
||||||
let two = run(&mut right, &mut right_state, frame);
|
|
||||||
assert_eq!(one, two, "seed {seed} round {round} in {metrics:?} at {room:?} scale {scale}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn wide(version: i64) -> SurfaceDocument {
|
|
||||||
let slab = |id: &str| match boxed(id, vec![]) {
|
|
||||||
Node::Box(mut slab) => {
|
|
||||||
slab.style.size = size2(px(1_500_000.0), px(10.0));
|
|
||||||
Node::Box(slab)
|
|
||||||
}
|
|
||||||
other => other,
|
|
||||||
};
|
|
||||||
let mut document = inline(version, boxed("root", vec![slab("left"), slab("right")]));
|
|
||||||
if let Node::Box(root) = &mut document.root {
|
|
||||||
root.style.direction = Direction::Row;
|
|
||||||
}
|
|
||||||
document
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_last_good_frame_is_cleared_by_a_delete_and_a_switch_and_kept_through_a_frame_error() {
|
|
||||||
let at = (800.0, 600.0);
|
|
||||||
let good = say(1, "fits");
|
|
||||||
// Kept through a room with no size: a refused layout afterwards still shows it.
|
|
||||||
let mut state = MemState::new();
|
|
||||||
state.put(&good.provider_id, &good);
|
|
||||||
let mut one = fresh(Metrics::Pixels);
|
|
||||||
show(&mut one, &good);
|
|
||||||
let first = run(&mut one, &mut state, input(at, 1.0));
|
|
||||||
run(&mut one, &mut state, input((f32::NAN, 600.0), 1.0));
|
|
||||||
state.put(&good.provider_id, &wide(2));
|
|
||||||
let held = run(&mut one, &mut state, input(at, 1.0));
|
|
||||||
assert_eq!(held.commands, first.commands);
|
|
||||||
assert_eq!(codes(&held), vec![Code::LayoutOutOfRange]);
|
|
||||||
|
|
||||||
// Cleared by a delete: what comes after has no frame to fall back on.
|
|
||||||
let mut state = MemState::new();
|
|
||||||
state.put(&good.provider_id, &good);
|
|
||||||
let mut two = fresh(Metrics::Pixels);
|
|
||||||
show(&mut two, &good);
|
|
||||||
run(&mut two, &mut state, input(at, 1.0));
|
|
||||||
state.delete(&surface_address(&good));
|
|
||||||
assert_eq!(run(&mut two, &mut state, input(at, 1.0)).commands, vec![]);
|
|
||||||
// The tombstone keeps the version: the same document again, and a different one at it, change nothing shown.
|
|
||||||
state.put(&good.provider_id, &good);
|
|
||||||
let replay = run(&mut two, &mut state, input(at, 1.0));
|
|
||||||
assert_eq!((codes(&replay), replay.commands), (vec![], vec![]));
|
|
||||||
state.put(&good.provider_id, &say(1, "other"));
|
|
||||||
let refused = run(&mut two, &mut state, input(at, 1.0));
|
|
||||||
assert_eq!((codes(&refused), refused.commands), (vec![Code::StaleVersionIgnored], vec![]));
|
|
||||||
state.put(&good.provider_id, &wide(2));
|
|
||||||
let out = run(&mut two, &mut state, input(at, 1.0));
|
|
||||||
assert_eq!((codes(&out), out.commands), (vec![Code::LayoutOutOfRange], vec![]));
|
|
||||||
|
|
||||||
// Cleared by a switch.
|
|
||||||
let other = {
|
|
||||||
let mut other = wide(1);
|
|
||||||
other.label = seg("other");
|
|
||||||
other
|
|
||||||
};
|
|
||||||
let mut state = MemState::new();
|
|
||||||
state.put(&good.provider_id, &good);
|
|
||||||
state.put(&other.provider_id, &other);
|
|
||||||
let mut three = fresh(Metrics::Pixels);
|
|
||||||
show(&mut three, &good);
|
|
||||||
run(&mut three, &mut state, input(at, 1.0));
|
|
||||||
show(&mut three, &other);
|
|
||||||
let switched = run(&mut three, &mut state, input(at, 1.0));
|
|
||||||
assert_eq!((codes(&switched), switched.commands), (vec![Code::LayoutOutOfRange], vec![]));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_switch_leaves_the_old_surface_holding_no_interest() {
|
|
||||||
let swarm = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
|
|
||||||
let other = say(1, "elsewhere");
|
|
||||||
let mut state = world(Fixture::F01SwarmDashboard);
|
|
||||||
state.put(&other.provider_id, &other);
|
|
||||||
let mut core = fresh(Metrics::Cells);
|
|
||||||
let at = (100.0, 37.0);
|
|
||||||
show(&mut core, &swarm);
|
|
||||||
run(&mut core, &mut state, input(at, 1.0));
|
|
||||||
let subscribed = count(&state, |call| matches!(call, Call::Subscribe(_)));
|
|
||||||
assert!(subscribed > 1, "f01 binds provider state, so more than its own record is held");
|
|
||||||
show(&mut core, &other);
|
|
||||||
run(&mut core, &mut state, input(at, 1.0));
|
|
||||||
let subscribes = count(&state, |call| matches!(call, Call::Subscribe(_)));
|
|
||||||
let unsubscribes = count(&state, |call| matches!(call, Call::Unsubscribe(_)));
|
|
||||||
assert_eq!(subscribes - unsubscribes, 1, "only the shown surface's own record is held");
|
|
||||||
// A record the old surface read now changes nothing and costs no read.
|
|
||||||
let summary = Swarm { id: "summary".into(), name: "Swarm".into(), load: 0.5 };
|
|
||||||
state.put_state(&ProviderId::new("provider.swarm"), "summary", &summary);
|
|
||||||
let before = state.calls().len();
|
|
||||||
run(&mut core, &mut state, input(at, 1.0));
|
|
||||||
assert_eq!(state.calls()[before..], [Call::Drain]);
|
|
||||||
}
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
# thing-core goldens
|
|
||||||
|
|
||||||
`resolve-*.bin` is a CultCache single-file store holding one resolved surface document under the
|
|
||||||
pinned clock; `resolve-*.txt` is the `{:#?}` text of the same document. The binary is the oracle and
|
|
||||||
the text is compared beside it. `THING_BLESS=1` through `thing_testkit::golden::check_with_text` is
|
|
||||||
the only way either changes.
|
|
||||||
|
|
@ -1,14 +0,0 @@
|
||||||
load visible bool true
|
|
||||||
load content text "42.0%"
|
|
||||||
minds visible bool true
|
|
||||||
minds#6:mind-1/mind-name visible bool true
|
|
||||||
minds#6:mind-1/mind-name content text "Eureka"
|
|
||||||
minds#6:mind-2/mind-name visible bool true
|
|
||||||
minds#6:mind-2/mind-name content text "Libby"
|
|
||||||
minds#6:mind-3/mind-name visible bool true
|
|
||||||
minds#6:mind-3/mind-name content text "Kiko"
|
|
||||||
restart visible bool true
|
|
||||||
restart enabled bool true
|
|
||||||
restart-label visible bool true
|
|
||||||
restart-label content text "Restart"
|
|
||||||
root visible bool true
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
enabled visible bool true
|
|
||||||
enabled checked bool true
|
|
||||||
port visible bool true
|
|
||||||
port placeholder text "port"
|
|
||||||
port initial text "8080"
|
|
||||||
root visible bool true
|
|
||||||
theme visible bool true
|
|
||||||
theme selected text "dark"
|
|
||||||
theme options options [dark=Dark, light=Light]
|
|
||||||
volume visible bool true
|
|
||||||
volume value number 40
|
|
||||||
|
|
@ -1,8 +0,0 @@
|
||||||
surface thing:surface:provider.swarm.dashboard viewport 100x37 scale 1 cells
|
|
||||||
root 0 0 100 6
|
|
||||||
load 0 0 50 1
|
|
||||||
minds#6:mind-1/mind-name 51 0 49 1
|
|
||||||
minds#6:mind-2/mind-name 0 2 50 1
|
|
||||||
minds#6:mind-3/mind-name 51 2 49 1
|
|
||||||
restart 0 3 50 3
|
|
||||||
restart-label 1 4 7 1
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue