Compare commits

..
185 changed files with 127 additions and 31337 deletions

View file

@ -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: |

7
.gitignore vendored
View file

@ -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/

212
Cargo.lock generated
View file

@ -17,30 +17,12 @@ version = "1.0.104"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
[[package]]
name = "ar_archive_writer"
version = "0.5.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec"
dependencies = [
"object",
]
[[package]] [[package]]
name = "autocfg" name = "autocfg"
version = "1.5.1" version = "1.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
[[package]]
name = "block-buffer"
version = "0.10.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
dependencies = [
"generic-array",
]
[[package]] [[package]]
name = "bumpalo" name = "bumpalo"
version = "3.20.3" version = "3.20.3"
@ -83,29 +65,10 @@ version = "0.8.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
[[package]]
name = "cpufeatures"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
dependencies = [
"libc",
]
[[package]]
name = "crypto-common"
version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
dependencies = [
"generic-array",
"typenum",
]
[[package]] [[package]]
name = "cultcache-rs" name = "cultcache-rs"
version = "0.3.1" version = "0.2.0"
source = "git+https://github.com/GameCult/CultLib.git?rev=4c9af401ae33812d862dde4ff3131433fc73c7dc#4c9af401ae33812d862dde4ff3131433fc73c7dc" source = "git+https://github.com/GameCult/CultLib.git?rev=b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7#b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"chrono", "chrono",
@ -116,33 +79,20 @@ dependencies = [
"serde", "serde",
"serde_bytes", "serde_bytes",
"serde_json", "serde_json",
"serde_stacker",
"sha2",
"stacker",
"uuid", "uuid",
"windows-sys 0.59.0", "windows-sys",
] ]
[[package]] [[package]]
name = "cultcache-rs-derive" name = "cultcache-rs-derive"
version = "0.2.0" version = "0.1.0"
source = "git+https://github.com/GameCult/CultLib.git?rev=4c9af401ae33812d862dde4ff3131433fc73c7dc#4c9af401ae33812d862dde4ff3131433fc73c7dc" source = "git+https://github.com/GameCult/CultLib.git?rev=b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7#b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
"syn 2.0.119", "syn 2.0.119",
] ]
[[package]]
name = "digest"
version = "0.10.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
]
[[package]] [[package]]
name = "find-msvc-tools" name = "find-msvc-tools"
version = "0.1.14" version = "0.1.14"
@ -183,16 +133,6 @@ dependencies = [
"slab", "slab",
] ]
[[package]]
name = "generic-array"
version = "0.14.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
dependencies = [
"typenum",
"version_check",
]
[[package]] [[package]]
name = "getrandom" name = "getrandom"
version = "0.4.3" version = "0.4.3"
@ -272,15 +212,6 @@ dependencies = [
"autocfg", "autocfg",
] ]
[[package]]
name = "object"
version = "0.39.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b"
dependencies = [
"memchr",
]
[[package]] [[package]]
name = "once_cell" name = "once_cell"
version = "1.21.4" version = "1.21.4"
@ -302,16 +233,6 @@ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]]
name = "psm"
version = "0.1.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622"
dependencies = [
"ar_archive_writer",
"cc",
]
[[package]] [[package]]
name = "quote" name = "quote"
version = "1.0.47" version = "1.0.47"
@ -355,12 +276,6 @@ dependencies = [
"serde", "serde",
] ]
[[package]]
name = "rustc-hash"
version = "2.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
[[package]] [[package]]
name = "rustversion" name = "rustversion"
version = "1.0.23" version = "1.0.23"
@ -420,28 +335,6 @@ dependencies = [
"zmij", "zmij",
] ]
[[package]]
name = "serde_stacker"
version = "0.1.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4936375d50c4be7eff22293a9344f8e46f323ed2b3c243e52f89138d9bb0f4a"
dependencies = [
"serde",
"serde_core",
"stacker",
]
[[package]]
name = "sha2"
version = "0.10.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[package]] [[package]]
name = "shlex" name = "shlex"
version = "2.0.1" version = "2.0.1"
@ -454,34 +347,6 @@ version = "0.4.12"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
[[package]]
name = "slotmap"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038"
dependencies = [
"version_check",
]
[[package]]
name = "smallvec"
version = "1.16.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59"
[[package]]
name = "stacker"
version = "0.1.25"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967"
dependencies = [
"cc",
"cfg-if",
"libc",
"psm",
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "syn" name = "syn"
version = "2.0.119" version = "2.0.119"
@ -504,18 +369,6 @@ dependencies = [
"unicode-ident", "unicode-ident",
] ]
[[package]]
name = "taffy"
version = "0.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cae92eb1b204bfd239b5c463e1bd2c3ce4913d2d3abfb5c64f5cfee9d65e5c68"
dependencies = [
"rustc-hash",
"serde",
"slotmap",
"smallvec",
]
[[package]] [[package]]
name = "thing-contract" name = "thing-contract"
version = "0.1.0" version = "0.1.0"
@ -525,48 +378,8 @@ dependencies = [
"rmp-serde", "rmp-serde",
"serde", "serde",
"serde_bytes", "serde_bytes",
"thing-testkit",
] ]
[[package]]
name = "thing-core"
version = "0.1.0"
dependencies = [
"stacker",
"taffy",
"thing-contract",
"thing-testkit",
]
[[package]]
name = "thing-state"
version = "0.1.0"
dependencies = [
"cultcache-rs",
"rmp-serde",
"serde",
"thing-core",
]
[[package]]
name = "thing-testkit"
version = "0.1.0"
dependencies = [
"anyhow",
"cultcache-rs",
"rmp-serde",
"serde",
"thing-contract",
"thing-core",
"thing-state",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]] [[package]]
name = "unicode-ident" name = "unicode-ident"
version = "1.0.26" version = "1.0.26"
@ -584,12 +397,6 @@ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]]
name = "version_check"
version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
[[package]] [[package]]
name = "wasm-bindgen" name = "wasm-bindgen"
version = "0.2.129" version = "0.2.129"
@ -725,15 +532,6 @@ dependencies = [
"windows-targets", "windows-targets",
] ]
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]] [[package]]
name = "windows-targets" name = "windows-targets"
version = "0.52.6" version = "0.52.6"

View file

@ -4,7 +4,6 @@ resolver = "2"
[workspace.dependencies] [workspace.dependencies]
anyhow = "1" anyhow = "1"
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "4c9af401ae33812d862dde4ff3131433fc73c7dc", package = "cultcache-rs" } cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7", package = "cultcache-rs" }
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
rmp-serde = "1.3" rmp-serde = "1.3"
taffy = { version = "0.16", default-features = false, features = ["std", "taffy_tree", "flexbox", "grid", "block_layout", "content_size"] }

View file

@ -1,41 +1,9 @@
# Thing # Thing
This repository is Thing (the Eve display, control and sensor edge for GameCult This repository is Thing. Its present tree is Thing 1, kept running for live
apps). Its present tree is Thing 1, kept running for live consumers until each consumers until each ports; Thing 2.0 is built here (`docs/thing2-target.md`).
ports; Thing 2.0 is built here (`docs/thing2-target.md`). The Thing 1 renderer The Thing 1 renderer repos are archived under their Eve names: EveUnity,
repos are archived under their Eve names: EveUnity, EveFlutter, EveElectron, EveFlutter, EveElectron, EveTui, EvePlugins and EveConformance.
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.
@ -246,8 +214,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 +226,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 +245,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

View file

@ -12,5 +12,4 @@ serde = { workspace = true }
serde_bytes = "0.11" serde_bytes = "0.11"
[dev-dependencies] [dev-dependencies]
thing-testkit = { path = "../thing-testkit" }
rmp-serde = { workspace = true } rmp-serde = { workspace = true }

View file

@ -28,7 +28,7 @@ pub struct AssetCatalog {
pub catalog_id: Segment, pub catalog_id: Segment,
#[cultcache(key = 2)] #[cultcache(key = 2)]
pub version: Version, pub version: Version,
#[cultcache(key = 3, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.AssetEntry>")] #[cultcache(key = 3)]
pub assets: Vec<AssetEntry>, pub assets: Vec<AssetEntry>,
} }

View file

@ -37,7 +37,6 @@ pub enum CommandRef {
/// A typed record of the declared `payload_schema`, as its MessagePack bytes. /// A typed record of the declared `payload_schema`, as its MessagePack bytes.
#[derive(Clone, Debug, PartialEq, CultSlots)] #[derive(Clone, Debug, PartialEq, CultSlots)]
#[cultcache(type_name = "GameCult.Thing.Contract.RecordPayload")]
pub struct RecordPayload { pub struct RecordPayload {
#[cultcache(key = 0)] #[cultcache(key = 0)]
pub schema: SchemaId, pub schema: SchemaId,
@ -106,7 +105,7 @@ pub struct CommandInvocation {
pub command: CommandId, pub command: CommandId,
#[cultcache(key = 4)] #[cultcache(key = 4)]
pub payload: RecordPayload, pub payload: RecordPayload,
#[cultcache(key = 5, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.CapturedInput>")] #[cultcache(key = 5)]
pub captured: Vec<CapturedInput>, pub captured: Vec<CapturedInput>,
#[cultcache(key = 6)] #[cultcache(key = 6)]
pub client: String, pub client: String,

View file

@ -9,7 +9,6 @@
use std::fmt; use std::fmt;
use cultcache_rs::CultTypeName;
use serde::{Deserialize, Deserializer, Serialize, Serializer, de}; use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
/// A value was outside its domain. Names the domain and its bound, never the value. /// A value was outside its domain. Names the domain and its bound, never the value.
@ -73,13 +72,6 @@ impl std::error::Error for DomainError {}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Seq(i32); pub struct Seq(i32);
impl CultTypeName for Seq {
fn cult_type_name() -> String {
"System.Int32".to_string()
}
const VALUE_TYPE: bool = true;
}
impl Seq { impl Seq {
pub const FIRST: Seq = Seq(1); pub const FIRST: Seq = Seq(1);
@ -116,13 +108,6 @@ impl Seq {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Version(i64); pub struct Version(i64);
impl CultTypeName for Version {
fn cult_type_name() -> String {
"System.Int64".to_string()
}
const VALUE_TYPE: bool = true;
}
impl Version { impl Version {
pub fn new(value: i64) -> Result<Self, DomainError> { pub fn new(value: i64) -> Result<Self, DomainError> {
if value >= 0 { Ok(Self(value)) } else { Err(DomainError::new("Version", "at least 0")) } if value >= 0 { Ok(Self(value)) } else { Err(DomainError::new("Version", "at least 0")) }
@ -181,12 +166,6 @@ impl Count {
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Segment(String); pub struct Segment(String);
impl CultTypeName for Segment {
fn cult_type_name() -> String {
"System.String".to_string()
}
}
impl Segment { impl Segment {
pub fn new(value: impl Into<String>) -> Result<Self, DomainError> { pub fn new(value: impl Into<String>) -> Result<Self, DomainError> {
let value = value.into(); let value = value.into();

View file

@ -1,6 +1,5 @@
//! Identifier newtypes and the record key of each kind. No caller spells a key as a free string. //! 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 serde::{Deserialize, Serialize};
use crate::domain::{Segment, Seq, Version}; use crate::domain::{Segment, Seq, Version};
@ -21,12 +20,6 @@ macro_rules! id_type {
&self.0 &self.0
} }
} }
impl CultTypeName for $name {
fn cult_type_name() -> String {
"System.String".to_string()
}
}
}; };
} }
@ -72,6 +65,6 @@ pub(crate) fn result_key(invocation_id: &str, seq: Seq) -> String {
format!("thing:result:{invocation_id}.{}", seq.get()) format!("thing:result:{invocation_id}.{}", seq.get())
} }
pub fn asset_catalog_key(provider: &ProviderId, catalog_id: &Segment) -> String { pub(crate) fn asset_catalog_key(provider: &ProviderId, catalog_id: &Segment) -> String {
format!("thing:asset_catalog:{}.{}", provider.as_str(), catalog_id.as_str()) format!("thing:asset_catalog:{}.{}", provider.as_str(), catalog_id.as_str())
} }

View file

@ -9,11 +9,10 @@
//! field types (`Seq`, `Version`, `Count`, `Segment`), whose `Deserialize` calls the same //! field types (`Seq`, `Version`, `Count`, `Segment`), whose `Deserialize` calls the same
//! `new` the constructors call, so no door skips a check. //! `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 //! Hazard: decoding these kinds from untrusted bytes on a default-size thread can abort the
//! once per level, so a hostile payload nested deep enough overflows the stack of a caller that //! process inside CultCache's nesting bound before the bound refuses (the stack is not
//! decodes it directly. CultCache refuses such a payload on read and on write //! bounded by nesting depth). The owner is `cultlib-gaps:follow_up:decode-stack-safety`; the
//! (`cultcache_rs::check_payload_depth`, 256 containers); a caller that decodes bytes outside a //! tests decode on a 16 MiB thread until it lands.
//! CultCache must run that check first.
mod asset; mod asset;
mod command; mod command;
@ -27,20 +26,12 @@ mod style;
pub use asset::*; pub use asset::*;
pub use command::*; pub use command::*;
pub use domain::{Count, DomainError, Segment, Seq, Version}; pub use domain::{Count, DomainError, Segment, Seq, Version};
pub use keys::{CommandId, NodeId, ProviderId, RecordKey, SchemaId, asset_catalog_key}; pub use keys::{CommandId, NodeId, ProviderId, RecordKey, SchemaId};
pub use node::*; pub use node::*;
pub use result::*; pub use result::*;
pub use source::*; pub use source::*;
pub use style::*; 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}; use cultcache_rs::{CultCache, CultCacheRegistry};
/// Registers the five kinds with a cache. /// Registers the five kinds with a cache.

View file

@ -1,14 +1,12 @@
//! Thing Script: the closed node union, the surface document that holds a tree of nodes, and the //! 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 //! composition document that names a reusable subtree. Arm keys are fixed for v1.
//! 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 cultcache_rs::{CultSlots, CultUnion, DatabaseEntry};
use crate::domain::{Count, Segment, Version}; use crate::domain::{Count, Segment, Version};
use crate::command::{CommandDecl, CommandRef}; use crate::command::{CommandDecl, CommandRef};
use crate::keys::{NodeId, ProviderId, composition_key, surface_key}; use crate::keys::{NodeId, ProviderId, composition_key, surface_key};
use crate::source::{Bind, BoolSource, CollectionSource, MemberPath, NumberSource, ParamName, TextSource}; use crate::source::{Bind, BoolSource, CollectionSource, MemberPath, NumberSource, TextSource};
use crate::style::{BoxStyle, Paint, Role}; use crate::style::{BoxStyle, Paint, Role};
/// What every node carries. /// What every node carries.
@ -23,7 +21,6 @@ pub struct NodeCommon {
} }
#[derive(Clone, Debug, PartialEq, CultUnion)] #[derive(Clone, Debug, PartialEq, CultUnion)]
#[cultcache(type_name = "GameCult.Thing.Contract.Node")]
pub enum Node { pub enum Node {
#[cultcache(key = 0)] #[cultcache(key = 0)]
Box(BoxNode), Box(BoxNode),
@ -51,8 +48,6 @@ pub enum Node {
Embed(EmbedNode), Embed(EmbedNode),
#[cultcache(key = 12)] #[cultcache(key = 12)]
Use(UseNode), Use(UseNode),
#[cultcache(key = 13)]
Slot(SlotNode),
} }
#[derive(Clone, Debug, PartialEq, CultSlots)] #[derive(Clone, Debug, PartialEq, CultSlots)]
@ -164,10 +159,8 @@ pub struct TextInputNode {
pub common: NodeCommon, pub common: NodeCommon,
#[cultcache(key = 1)] #[cultcache(key = 1)]
pub multiline: bool, 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)] #[cultcache(key = 2)]
pub input_kind: InputKind, pub kind: InputKind,
#[cultcache(key = 3)] #[cultcache(key = 3)]
pub placeholder: TextSource, pub placeholder: TextSource,
#[cultcache(key = 4)] #[cultcache(key = 4)]
@ -316,13 +309,6 @@ pub struct CompositionRef {
pub version: Version, 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)] #[derive(Clone, Debug, PartialEq, CultSlots)]
pub struct UseNode { pub struct UseNode {
#[cultcache(key = 0)] #[cultcache(key = 0)]
@ -333,15 +319,6 @@ pub struct UseNode {
pub args: Vec<Arg>, 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)] #[derive(Clone, Debug, PartialEq, CultSlots)]
pub struct Arg { pub struct Arg {
#[cultcache(key = 0)] #[cultcache(key = 0)]
@ -445,7 +422,7 @@ pub struct SurfaceDocument {
pub title: String, pub title: String,
#[cultcache(key = 4)] #[cultcache(key = 4)]
pub root: Node, pub root: Node,
#[cultcache(key = 5, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.CommandDecl>")] #[cultcache(key = 5)]
pub commands: Vec<CommandDecl>, pub commands: Vec<CommandDecl>,
} }
@ -465,7 +442,7 @@ pub struct CompositionDocument {
pub name: Segment, pub name: Segment,
#[cultcache(key = 2)] #[cultcache(key = 2)]
pub version: Version, pub version: Version,
#[cultcache(key = 3, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.ParamDecl>")] #[cultcache(key = 3)]
pub params: Vec<ParamDecl>, pub params: Vec<ParamDecl>,
#[cultcache(key = 4)] #[cultcache(key = 4)]
pub body: Node, pub body: Node,

View file

@ -41,7 +41,6 @@ pub struct FailedOutcome {
} }
#[derive(Clone, Debug, PartialEq, CultUnion)] #[derive(Clone, Debug, PartialEq, CultUnion)]
#[cultcache(type_name = "GameCult.Thing.Contract.Outcome")]
pub enum Outcome { pub enum Outcome {
#[cultcache(key = 0)] #[cultcache(key = 0)]
Pending(PendingOutcome), Pending(PendingOutcome),

View file

@ -81,9 +81,7 @@ pub enum StateSource {
Item, Item,
} }
/// A state record. An absent provider is the publisher of the document. `schema` is the id the /// A state record. An absent provider is the publisher of the document.
/// 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)] #[derive(Clone, Debug, PartialEq, CultSlots)]
pub struct StateRef { pub struct StateRef {
#[cultcache(key = 0)] #[cultcache(key = 0)]

View file

@ -1,60 +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 the_written_store_carries_the_rows() {
// goldens.rs writes a store of one record per kind and compares it byte for byte with the
// committed surface.cc, so the committed file's catalog is the catalog the crate writes. It is
// copied first: reading a store creates a lock file beside it.
let committed = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens/surface.cc");
let work = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("catalog-members");
std::fs::create_dir_all(&work).unwrap();
let copy = work.join("surface.cc");
std::fs::copy(committed, &copy).unwrap();
let catalog = SingleFileMessagePackBackingStore::new(&copy).pull_schema_catalog().unwrap();
let from_store = sorted(catalog.iter().map(|entry| group(&entry.members)).collect());
assert_eq!(from_store, tsv_groups());
let _ = std::fs::remove_dir_all(&work);
}

View file

@ -1,5 +1,7 @@
//! Constructors for the values the contract goldens, the fixtures and the other tests share. //! Constructors for the values the goldens and the other tests share. Every value is built
//! Every value is built through the crate's public types; no bytes are spelled here. //! through the crate's public types; no bytes are spelled here.
#![allow(dead_code)]
use thing_contract::*; use thing_contract::*;

View file

@ -2,24 +2,42 @@
//! byte. The TypeScript and C# packages and core are held to these files; none of them writes //! 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. //! one. `THING_BLESS=1` rewrites them; any other run compares.
mod common;
use std::collections::BTreeSet; use std::collections::BTreeSet;
use std::fmt::Debug; use std::fmt::Debug;
use std::path::PathBuf; use std::path::PathBuf;
use thing_testkit::{build::*, golden, store}; use common::*;
use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry}; use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry, SingleFileMessagePackBackingStore};
use thing_contract::*; use thing_contract::*;
const PINNED_CLOCK: &str = "2026-01-01T00:00:00Z";
// A value that must never appear in a refusal.
const CANARY: &str = "CANARY-7f3a91c2";
fn goldens_dir() -> PathBuf { fn goldens_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens") PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
} }
// A value that must never appear in a refusal. fn blessing() -> bool {
const CANARY: &str = "CANARY-7f3a91c2"; std::env::var("THING_BLESS").as_deref() == Ok("1")
}
/// Bless the file or compare against it. Returns the committed bytes.
fn golden_bytes(file: &str, produced: &[u8]) -> Vec<u8> {
let path = goldens_dir().join(file);
if blessing() {
std::fs::write(&path, produced).unwrap_or_else(|error| panic!("{file}: {error}"));
}
let committed = std::fs::read(&path).unwrap_or_else(|error| panic!("{file}: {error}"));
assert_eq!(committed, produced, "{file}: the committed golden differs from what the crate writes");
committed
}
fn golden<T: DatabaseEntry + PartialEq + Debug>(name: &str, value: &T) -> String { fn golden<T: DatabaseEntry + PartialEq + Debug>(name: &str, value: &T) -> String {
let produced = rmp_serde::to_vec(value).unwrap(); let produced = rmp_serde::to_vec(value).unwrap();
let committed = golden::check(&goldens_dir(), &format!("{name}.bin"), &produced); let committed = golden_bytes(&format!("{name}.bin"), &produced);
let decoded: T = rmp_serde::from_slice(&committed).unwrap_or_else(|error| panic!("{name}: {error}")); 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!(&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"); assert_eq!(rmp_serde::to_vec(&decoded).unwrap(), committed, "{name}: re-encoding changed the bytes");
@ -132,7 +150,7 @@ fn full_surface() -> SurfaceDocument {
Node::TextInput(TextInputNode { Node::TextInput(TextInputNode {
common: common("name-input"), common: common("name-input"),
multiline: true, multiline: true,
input_kind: InputKind::Number, kind: InputKind::Number,
placeholder: lit_text("name"), placeholder: lit_text("name"),
initial: TextSource::Param(param("initial")), initial: TextSource::Param(param("initial")),
submit: command("rename"), submit: command("rename"),
@ -140,7 +158,7 @@ fn full_surface() -> SurfaceDocument {
Node::TextInput(TextInputNode { Node::TextInput(TextInputNode {
common: common("title-input"), common: common("title-input"),
multiline: false, multiline: false,
input_kind: InputKind::Text, kind: InputKind::Text,
placeholder: lit_text("title"), placeholder: lit_text("title"),
initial: TextSource::Param(param("initial")), initial: TextSource::Param(param("initial")),
submit: command("retitle"), submit: command("retitle"),
@ -366,10 +384,7 @@ fn full_composition() -> CompositionDocument {
.into_iter() .into_iter()
.map(|(name, kind)| ParamDecl { name: name.into(), kind }) .map(|(name, kind)| ParamDecl { name: name.into(), kind })
.collect(), .collect(),
body: boxed( body: boxed("panel-root", vec![text("panel-title", "t"), inner_use]),
"panel-root",
vec![text("panel-title", "t"), inner_use, Node::Slot(SlotNode { param: param("body") })],
),
} }
} }
@ -420,17 +435,26 @@ fn asset_catalog() -> AssetCatalog {
/// A store with one record of each kind, written by cultcache-rs under a pinned clock. /// A store with one record of each kind, written by cultcache-rs under a pinned clock.
fn write_store(path: &std::path::Path) { fn write_store(path: &std::path::Path) {
let mut cache = store::create(path); let _ = std::fs::remove_file(path);
let mut cache = CultCache::new();
ThingContract.register_entries(&mut cache).unwrap();
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap();
let surface = full_surface(); let surface = full_surface();
let composition = full_composition(); let composition = full_composition();
let invocation = invocation(); let invocation = invocation();
let result = CommandResult::pending(&invocation, seq(1), "working"); let result = CommandResult::pending(&invocation, seq(1), "working");
let catalog = asset_catalog(); let catalog = asset_catalog();
store::put_pinned(&mut cache, &surface.record_key(), &surface); put(&mut cache, &surface.record_key(), &surface);
store::put_pinned(&mut cache, &composition.record_key(), &composition); put(&mut cache, &composition.record_key(), &composition);
store::put_pinned(&mut cache, &invocation.record_key(), &invocation); put(&mut cache, &invocation.record_key(), &invocation);
store::put_pinned(&mut cache, &result.record_key(), &result); put(&mut cache, &result.record_key(), &result);
store::put_pinned(&mut cache, &catalog.record_key(), &catalog); put(&mut cache, &catalog.record_key(), &catalog);
}
fn put<T: DatabaseEntry>(cache: &mut CultCache, key: &str, value: &T) {
let (mut envelope, _) = cache.prepare_entry(key, value).unwrap();
envelope.stored_at = PINNED_CLOCK.into();
cache.put_envelope::<T>(envelope).unwrap();
} }
fn envelope<T: DatabaseEntry>(key: &str, payload: Vec<u8>) -> CultCacheEnvelope { fn envelope<T: DatabaseEntry>(key: &str, payload: Vec<u8>) -> CultCacheEnvelope {
@ -438,17 +462,17 @@ fn envelope<T: DatabaseEntry>(key: &str, payload: Vec<u8>) -> CultCacheEnvelope
key: key.into(), key: key.into(),
r#type: T::TYPE.into(), r#type: T::TYPE.into(),
payload, payload,
stored_at: store::PINNED_CLOCK.into(), stored_at: PINNED_CLOCK.into(),
schema_id: Some(T::TYPE.into()), schema_id: Some(T::TYPE.into()),
} }
} }
#[test] fn open_store(path: &std::path::Path) -> CultCache {
fn slot_arm_bytes() { let mut cache = CultCache::new();
let slot = Node::Slot(SlotNode { param: param("body") }); ThingContract.register_entries(&mut cache).unwrap();
let bytes = rmp_serde::to_vec(&slot).unwrap(); cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap();
assert_eq!(bytes, [0x92, 0x0D, 0x91, 0x91, 0xA4, 0x62, 0x6F, 0x64, 0x79]); cache.pull_all_backing_stores().unwrap();
assert_eq!(rmp_serde::from_slice::<Node>(&bytes).unwrap(), slot); cache
} }
#[test] #[test]
@ -467,7 +491,7 @@ fn goldens_match() {
// that no case names is an orphan. // that no case names is an orphan.
let refusals = refusal_payloads(); let refusals = refusal_payloads();
for (name, bytes) in &refusals { for (name, bytes) in &refusals {
golden::check(&goldens_dir(), &format!("{name}.bin"), bytes); golden_bytes(&format!("{name}.bin"), bytes);
names.insert((*name).to_string()); names.insert((*name).to_string());
} }
let on_disk: BTreeSet<String> = std::fs::read_dir(goldens_dir()) let on_disk: BTreeSet<String> = std::fs::read_dir(goldens_dir())
@ -480,10 +504,10 @@ fn goldens_match() {
// The store: one record of each kind, written under a pinned clock, byte for byte. // 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"); let scratch = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("goldens-surface.cc");
write_store(&scratch); write_store(&scratch);
let committed = golden::check(&goldens_dir(), "surface.cc", &std::fs::read(&scratch).unwrap()); let committed = golden_bytes("surface.cc", &std::fs::read(&scratch).unwrap());
let reopened = goldens_dir().join("surface.cc"); let reopened = goldens_dir().join("surface.cc");
assert_eq!(std::fs::read(&reopened).unwrap(), committed); assert_eq!(std::fs::read(&reopened).unwrap(), committed);
let cache = store::open(&scratch); let cache = open_store(&scratch);
let surface = full_surface(); let surface = full_surface();
assert_eq!(cache.get::<SurfaceDocument>(&surface.record_key()).unwrap(), Some(surface)); assert_eq!(cache.get::<SurfaceDocument>(&surface.record_key()).unwrap(), Some(surface));
let composition = full_composition(); let composition = full_composition();
@ -529,11 +553,10 @@ fn refusal_payloads() -> Vec<(&'static str, Vec<u8>)> {
let root = text("root", "x"); let root = text("root", "x");
vec![ vec![
("result-thing1-flat", rmp_serde::to_vec_named(&flat).unwrap()), ("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 // A surface whose root is an arm key the Node union does not declare.
// Node does not declare (Slot is 13).
( (
"node-unknown-arm", "node-unknown-arm",
rmp_serde::to_vec(&("provider.a", "main", 1i64, CANARY, (14i32, (CANARY,)), unit)).unwrap(), rmp_serde::to_vec(&("provider.a", "main", 1i64, CANARY, (13i32, (CANARY,)), unit)).unwrap(),
), ),
// A result whose outcome is an arm key the Outcome union does not declare. // 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()), ("outcome-unknown-arm", rmp_serde::to_vec(&("inv-1", 1i32, (4i32, (CANARY,)))).unwrap()),
@ -568,7 +591,7 @@ fn refusal_payloads() -> Vec<(&'static str, Vec<u8>)> {
#[test] #[test]
fn refusal_cases() { fn refusal_cases() {
let payloads: std::collections::BTreeMap<_, _> = refusal_payloads().into_iter().collect(); let payloads: std::collections::BTreeMap<_, _> = refusal_payloads().into_iter().collect();
let committed = |name: &str| golden::check(&goldens_dir(), &format!("{name}.bin"), &payloads[name]); let committed = |name: &str| golden_bytes(&format!("{name}.bin"), &payloads[name]);
// Stored under their key, each is refused naming the kind and the key, never a value. // Stored under their key, each is refused naming the kind and the key, never a value.
let cases: [(&str, &str, &str); 7] = [ let cases: [(&str, &str, &str); 7] = [
@ -600,7 +623,7 @@ fn refusal_cases() {
} }
// Decoded directly, the refusal names the union and the arm key, and never the payload. // 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")] { for (name, union, key) in [("node-unknown-arm", "Node", "13"), ("outcome-unknown-arm", "Outcome", "4")] {
let bytes = committed(name); let bytes = committed(name);
let message = if union == "Node" { let message = if union == "Node" {
rmp_serde::from_slice::<SurfaceDocument>(&bytes).unwrap_err().to_string() rmp_serde::from_slice::<SurfaceDocument>(&bytes).unwrap_err().to_string()
@ -642,6 +665,13 @@ fn refusal_cases() {
#[test] #[test]
fn deep_tree() { fn deep_tree() {
// Decoding a Node costs tens of KiB of debug stack per nesting level, so the chain runs on a
// thread that has the room; the 2 MiB default does not. The hazard is CultCache's, owned by
// cultlib-gaps:follow_up:decode-stack-safety; the test stays on the big thread until it lands.
std::thread::Builder::new().stack_size(16 * 1024 * 1024).spawn(deep_tree_body).unwrap().join().unwrap();
}
fn deep_tree_body() {
// A 64-deep Box chain. // A 64-deep Box chain.
let mut chain = text("leaf", "bottom"); let mut chain = text("leaf", "bottom");
for depth in (0..64).rev() { for depth in (0..64).rev() {
@ -668,12 +698,15 @@ fn deep_tree() {
}; };
let path = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("deep-tree.cc"); let path = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("deep-tree.cc");
let _ = std::fs::remove_file(&path);
{ {
let mut cache = store::create(&path); let mut cache = CultCache::new();
store::put_pinned(&mut cache, &deep.record_key(), &deep); ThingContract.register_entries(&mut cache).unwrap();
store::put_pinned(&mut cache, &wide.record_key(), &wide); cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap();
put(&mut cache, &deep.record_key(), &deep);
put(&mut cache, &wide.record_key(), &wide);
} }
let cache = store::open(&path); let cache = open_store(&path);
assert_eq!(cache.get::<SurfaceDocument>(&deep.record_key()).unwrap(), Some(deep)); assert_eq!(cache.get::<SurfaceDocument>(&deep.record_key()).unwrap(), Some(deep));
assert_eq!(cache.get::<SurfaceDocument>(&wide.record_key()).unwrap(), Some(wide)); assert_eq!(cache.get::<SurfaceDocument>(&wide.record_key()).unwrap(), Some(wide));
} }

View file

@ -12,8 +12,8 @@ when absent. Arm keys are fixed for v1.
| File | Kind | Decodes to | | 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 | | `surface-all-arms.bin` | `gamecult.thing.surface.v1` | One surface with all 13 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), 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 | | `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 |
| `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 | | `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 |
| `result-pending.bin` | `gamecult.thing.command_result.v1` | Outcome Pending, seq 1 | | `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.bin` | same | Outcome Completed with source version 8, drafts cleared, no effect |
@ -30,7 +30,7 @@ when absent. Arm keys are fixed for v1.
| File | Payload | Expected | | 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 | | `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 | | `node-unknown-arm.bin` | a surface whose root node has arm key 13, 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 13, 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 | | `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-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 | | `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 |
@ -40,9 +40,3 @@ when absent. Arm keys are fixed for v1.
| `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 | | `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. 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 except `surface.cc` (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.

File diff suppressed because it is too large Load diff

View file

@ -1 +1 @@
–ªprovider.a¤main¯CANARY-7f3a91c2’‘¯CANARY-7f3a91c2<63> –ªprovider.a¤main¯CANARY-7f3a91c2’ ‘¯CANARY-7f3a91c2<63>

View file

@ -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")
}

View file

@ -1,4 +1,6 @@
use thing_testkit::build::*; mod common;
use common::*;
use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry, decode_payload}; use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry, decode_payload};
use serde::Deserialize; use serde::Deserialize;
use serde::de::IntoDeserializer; use serde::de::IntoDeserializer;

View file

@ -1,16 +0,0 @@
[package]
name = "thing-core"
version = "0.1.0"
edition = "2024"
license = "MIT"
publish = false
# Normal dependencies are thing-contract, stacker and taffy: layout is 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
[dev-dependencies]
thing-testkit = { path = "../thing-testkit" }

View file

@ -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]");
}
}

View file

@ -1,346 +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 walk;
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.
#[derive(Clone, Debug, PartialEq)]
pub struct Instance {
pub key: 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)
}
}

View file

@ -1,199 +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();
(format!("!{record}"), format!("{id}!{}:{record}/", record.len()))
}
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 = format!("{id}#{}:{key}/", key.len());
(key, prefix)
}
};
let mut root = (*repeat.template).clone();
rewrite(&mut root, &prefix, &inside);
built.push((Instance { key, 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())
}
}

View file

@ -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)
}
}

View file

@ -1,65 +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,
}
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)
}
}
/// 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,
}

View file

@ -1,183 +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;
/// 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 },
Plot { node: &'a NodeId },
}
/// 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: String, 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 one place logical units become device units and back: `k` device px per logical px
/// (1 in Cells). 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, one cell.
pub(super) fn placeholder(self) -> f32 {
if self.cells { 1.0 } else { self.px(16.0) }
}
pub(super) fn px(self, logical: f32) -> f32 {
logical * self.k
}
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(()),
}
}

View file

@ -1,216 +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. 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::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>,
}
/// 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 main = tree::build(tree, dev, tree::Top::Document, (vw, vh), measure);
let overlays = solve(tree, main, 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 })
}
/// Solve one built 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.
#[allow(clippy::too_many_arguments)]
fn solve<'a>(
tree: &BoundTree,
mut built: tree::Built<'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 tree::Built { taffy, root, entries, leaves, diagnostics: own, overlays } = &mut 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")
});
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);
absolute.push((x, y));
let (w, h) = (laid.size.width, laid.size.height);
// 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),
});
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,
});
}
diagnostics.append(own);
Ok(std::mem::take(overlays))
}

View file

@ -1,56 +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::{self, 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 built = tree::build(tree, dev, Top::Overlay(overlay), (anchor.w, anchor.h), measure);
let start = nodes.len();
let nested = solve(tree, built, 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(())
}

View file

@ -1,289 +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::{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, negative: bool) -> Option<f32> {
number(scalar.value, negative).map(|v| dev.px(v)).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) -> Option<LengthPercentage> {
match d {
c::Dimension::Px(s) => length(s, dev, false).map(LengthPercentage::length),
c::Dimension::Percent(s) => percent(s, false).map(LengthPercentage::percent),
_ => None,
}
}
fn lpa(d: &c::Dimension, dev: Device, negative: bool) -> Option<LengthPercentageAuto> {
match d {
c::Dimension::Px(s) => length(s, dev, 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) -> Option<Dimension> {
match d {
c::Dimension::Px(s) => length(s, dev, 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) -> Option<Dimension> {
match d {
c::Dimension::Content => Some(Dimension::content()),
c::Dimension::Fr(_) => None,
other => size_dim(other, dev),
}
}
fn track(d: &c::Dimension, dev: Device) -> 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, 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), Dimension::auto()),
height: self.take(field, size_dim(&s.height, dev), 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, false), LengthPercentageAuto::auto()),
height: self.take(field, lpa(&s.height, dev, 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, negative), initial),
right: self.take(field, lpa(&e.right, dev, negative), initial),
top: self.take(field, lpa(&e.top, dev, negative), initial),
bottom: self.take(field, lpa(&e.bottom, dev, 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), zero),
right: self.take(field, lp(&e.right, dev), zero),
top: self.take(field, lp(&e.top, dev), zero),
bottom: self.take(field, lp(&e.bottom, dev), zero),
}
}
fn tracks(&mut self, field: &'static str, dims: &[c::Dimension]) -> Vec<GridTemplateComponent<String>> {
let dev = self.dev;
let tracks: Option<Vec<_>> = dims.iter().map(|d| track(d, dev)).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.
pub(super) fn box_style(s: &c::BoxStyle, paint: &c::Paint, dev: Device) -> (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() };
let border = match &paint.border {
None => LengthPercentage::ZERO,
Some(b) => {
let width = slots.take("border", length(&c::Scalar { value: b.width }, dev, false), 0.0);
LengthPercentage::length(width)
}
};
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), LengthPercentage::ZERO);
let height = slots.take("gap", lp(&gap.height, dev), 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, right: border, top: border, bottom: border },
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);
slots.take("basis", basis, Dimension::auto())
},
grid_template_columns: slots.tracks("grid_columns", grid_columns).into_iter().collect(),
grid_template_rows: slots.tracks("grid_rows", 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| {
let v = slots.take("size", length(&c::Scalar { value }, dev, false), 0.0);
(Dimension::length(v), LengthPercentageAuto::length(v))
};
let (w, wa) = side(&mut slots, width);
let (h, ha) = side(&mut slots, height);
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)
}

View file

@ -1,286 +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::{Node, NodeId, Overflow, OverlayNode};
use super::measure::{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,
}
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>,
}
/// What the Taffy tree is rooted at: the viewport holding the document root, or one Overlay.
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(),
};
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, '_> {
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 });
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 index = self.entry(id, parent, &Overflow::Visible);
let context = self.leaves.len();
self.leaves.push(leaf);
let node = self.taffy.new_leaf_with_context(style, context).expect("taffy: insert");
self.entries[index].node = node;
out.push(node);
}
fn container(
&mut self,
id: &'a NodeId,
parent: Option<usize>,
(style, invalid): (Style, Invalid),
overflow: &Overflow,
children: &'a [Node],
out: &mut Vec<taffy::NodeId>,
) {
self.report(id, invalid);
let index = self.entry(id, parent, overflow);
let mut kids = Vec::new();
for child in children {
self.visit(child, Some(index), &mut kids);
}
let node = self.taffy.new_with_children(style, &kids).expect("taffy: insert");
self.entries[index].node = node;
out.push(node);
}
/// 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.container(&b.common.id, parent, style, &b.style.overflow, &b.children, out);
}
}
Node::Button(b) => {
if !self.hidden(&b.common.id) {
self.container(&b.common.id, parent, (Style::default(), Vec::new()), &Overflow::Visible, &b.content, out);
}
}
// 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 least = taffy::LengthPercentageAuto::length(self.dev.placeholder());
let style = Style { min_size: taffy::Size { width: least, height: 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) {
self.leaf(&n.common.id, parent, Leaf::Plot { node: &n.common.id }, out);
}
}
})
}
}

View file

@ -1,10 +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 diagnostic;
pub mod layout;
pub mod port;
pub mod render;
pub mod resolve;
pub mod theme;

View file

@ -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)
}
}

View file

@ -1,146 +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.
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>;
}
#[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")));
}
}

View file

@ -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,
}
}
}

View file

@ -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
}

View file

@ -1,317 +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 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::diagnostic::{Code, Diagnostic};
use crate::layout::{LaidTree, MAX_DEVICE, Measure, Metrics, Rect, TextRequest};
use crate::resolve::grow;
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,
}
/// 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>,
}
pub fn render(tree: &BoundTree, laid: &LaidTree, input: &RenderInput, text: &mut dyn Measure) -> Rendered {
let mut nodes = HashMap::new();
index(tree, &tree.resolved().document().root, &mut nodes);
let k = match input.metrics {
Metrics::Pixels if input.scale.is_finite() && input.scale > 0.0 => input.scale,
_ => 1.0,
};
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
}
/// Every node of the document by id, Repeat instances included (ids are unique after resolve).
fn index<'a>(tree: &'a BoundTree, node: &'a Node, out: &mut HashMap<&'a NodeId, &'a Node>) {
grow(|| {
let (id, children): (&NodeId, &[Node]) = match node {
Node::Box(n) => (&n.common.id, &n.children),
Node::Button(n) => (&n.common.id, &n.content),
Node::Overlay(n) => (&n.common.id, &n.children),
Node::Repeat(n) => {
for instance in tree.instances(&n.common.id) {
index(tree, &instance.root, out);
}
(&n.common.id, &[])
}
Node::Text(n) => (&n.common.id, &[]),
Node::Image(n) => (&n.common.id, &[]),
Node::Toggle(n) => (&n.common.id, &[]),
Node::Slider(n) => (&n.common.id, &[]),
Node::TextInput(n) => (&n.common.id, &[]),
Node::Select(n) => (&n.common.id, &[]),
Node::Plot(n) => (&n.common.id, &[]),
Node::Embed(n) => (&n.common.id, &[]),
Node::Use(n) => (&n.common.id, &[]),
Node::Slot(_) => return,
};
out.insert(id, node);
for child in children {
index(tree, child, 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 })
}
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 }
}
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(),
}
}
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 };
self.paint(node, rect, text);
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);
}
}
fn paint(&mut self, node: &'a Node, rect: Rect, 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) => {
let color = self.named(&u.common.id, "thing.placeholder");
self.out.commands.push(RenderCommand::FillRect { rect, radius: 0.0, color });
let color = self.named(&u.common.id, "thing.error");
self.out.commands.push(RenderCommand::StrokeRect { rect, radius: 0.0, width: 1.0, color });
}
Node::Text(n) => {
let tree = self.tree;
match tree.value(&n.common.id, Field::Content) {
Some(Bound::Text(content)) => {
let color = match self.input.theme.text.get(&n.style_token) {
Some(style) => style.color.clone(),
None => self.fault(&n.common.id, &n.style_token),
};
let request = TextRequest {
node: &n.common.id,
text: content,
style_token: &n.style_token,
wrap: n.wrap,
max_lines: n.max_lines.map(|lines| lines.get().max(0) as u32),
};
for line in text.text(&request, rect.w).lines {
let origin = (rect.x, rect.y + line.y);
self.out.commands.push(RenderCommand::Text { origin, run: line.run, color: color.clone() });
}
}
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 });
}
_ => {}
}
}
// Button, Toggle, Slider, Select, TextInput, Image and Plot draw nothing until the leaves cut.
_ => {}
}
}
/// 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 { 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 });
}
}
}

View file

@ -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),
}
}
}

View file

@ -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(&param.name, &param.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(""),
}
}

View file

@ -1,131 +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>,
}
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())
}
/// 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) -> Vec<Diagnostic> {
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),
_ => Vec::new(),
},
Change::Delete(address) => {
// A tombstone: the highest version stays so an older one is not taken again,
// but the tree and the interests go.
if let Some(held) = self.surfaces.get_mut(address.key.as_str()) {
held.tree = None;
let released = std::mem::take(&mut held.interests);
ledger.diff(port, &released, &HashSet::new());
}
Vec::new()
}
Change::Refused(refusal) => vec![Diagnostic {
code: Code::DecodeRefused,
surface: address.key.as_str().to_string(),
node: None,
detail: refusal.detail.clone(),
}],
};
}
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 diagnostics = Vec::new();
for key in readers {
let document = self.surfaces[&key].document.clone();
diagnostics.extend(self.resolve_held(&key, document, port, ledger));
}
diagnostics
}
fn offer(&mut self, document: &SurfaceDocument, port: &mut dyn StatePort, ledger: &mut Ledger) -> Vec<Diagnostic> {
let key = document.record_key();
if let Some(held) = self.surfaces.get_mut(&key)
&& document.version <= held.document.version
{
return 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()
};
}
self.resolve_held(&key, document.clone(), port, ledger)
}
/// 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.
fn resolve_held(&mut self, key: &str, document: SurfaceDocument, port: &mut dyn StatePort, ledger: &mut Ledger) -> Vec<Diagnostic> {
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;
if let Some(tree) = resolution.tree {
held.tree = Some(tree);
}
resolution.diagnostics
}
}

View file

@ -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::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, 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 }
}

View file

@ -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]))
}

View file

@ -1,110 +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::{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. A tree deeper than the limit is not walked further.
pub(super) fn check(root: &Node, 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 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 !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)));
}
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`.
}
}

View file

@ -1,84 +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.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)),
]
.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()
}
}

File diff suppressed because it is too large Load diff

View file

@ -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.

View file

@ -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

View file

@ -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

View file

@ -1,8 +0,0 @@
surface thing:surface:provider.swarm.dashboard viewport 100x37 scale 1 cells
root 0 0 100 23
load 2 2 48 1
minds#6:mind-1/mind-name 54 2 48 1
minds#6:mind-2/mind-name 2 11 48 1
minds#6:mind-3/mind-name 54 11 48 1
restart 2 20 48 1
restart-label 2 20 7 1

View file

@ -1,8 +0,0 @@
surface thing:surface:provider.swarm.dashboard viewport 800x600 scale 1.5 pixels
root 0 0 1200 102
load 3 3 597 24
minds#6:mind-1/mind-name 606 3 597 24
minds#6:mind-2/mind-name 3 39 597 24
minds#6:mind-3/mind-name 606 39 597 24
restart 3 75 597 24
restart-label 3 75 84 24

View file

@ -1,8 +0,0 @@
surface thing:surface:provider.swarm.dashboard viewport 800x600 scale 2 pixels
root 0 0 1600 136
load 4 4 796 32
minds#6:mind-1/mind-name 808 4 796 32
minds#6:mind-2/mind-name 4 52 796 32
minds#6:mind-3/mind-name 808 52 796 32
restart 4 100 796 32
restart-label 4 100 112 32

View file

@ -1,8 +0,0 @@
surface thing:surface:provider.swarm.dashboard viewport 800x600 scale 1 pixels
root 0 0 800 68
load 2 2 398 16
minds#6:mind-1/mind-name 404 2 398 16
minds#6:mind-2/mind-name 2 26 398 16
minds#6:mind-3/mind-name 404 26 398 16
restart 2 50 398 16
restart-label 2 50 56 16

View file

@ -1,5 +0,0 @@
surface thing:surface:provider.login.login viewport 800x600 scale 1 pixels
root 0 0 800 52
username 2 2 796 24
sign-in-button 2 34 796 16
sign-in-button-label 2 34 56 16

View file

@ -1,5 +0,0 @@
surface thing:surface:provider.muninn.input-target viewport 800x600 scale 1 pixels
root 80 0 640 360
board 82 2 636 360
target 280 120 48 48
target-label 282 122 44 16

View file

@ -1,6 +0,0 @@
surface thing:surface:provider.settings.form viewport 800x600 scale 1 pixels
root 0 0 800 116
enabled 2 2 796 20
volume 2 30 796 20
theme 2 58 796 24
port 2 90 796 24

View file

@ -1,11 +0,0 @@
surface thing:surface:provider.dialog.modal viewport 800x600 scale 1.5 pixels
root 0 0 1200 30
page-text 3 3 1194 24
overlay confirm-overlay anchor viewport
confirm-overlay 0 0 1200 900
dialog 0 399 1200 102
dialog-title 3 402 1194 24
confirm 3 438 1194 24
confirm-label 3 438 72 24
cancel 3 474 1194 24
cancel-label 3 474 72 24

View file

@ -1,11 +0,0 @@
surface thing:surface:provider.dialog.modal viewport 800x600 scale 1 pixels
root 0 0 800 20
page-text 2 2 796 16
overlay confirm-overlay anchor viewport
confirm-overlay 0 0 800 600
dialog 0 266 800 68
dialog-title 2 268 796 16
confirm 2 292 796 16
confirm-label 2 292 48 16
cancel 2 316 796 16
cancel-label 2 316 48 16

File diff suppressed because it is too large Load diff

View file

@ -1,5 +0,0 @@
surface thing:surface:provider.market.plot viewport 800x600 scale 1 pixels
root 0 0 800 20
line 2 2 796 0
bar 2 10 796 0
area 2 18 796 0

View file

@ -1,5 +0,0 @@
surface thing:surface:provider.viewport.embed-viewport viewport 800x600 scale 1.5 pixels
root 0 0 1200 276
before 3 3 72 270
viewport 366 3 480 270
after 1137 3 60 270

View file

@ -1,5 +0,0 @@
surface thing:surface:provider.viewport.embed-viewport viewport 800x600 scale 1 pixels
root 0 0 800 184
before 2 2 48 180
viewport 244 2 320 180
after 758 2 40 180

View file

@ -1,14 +0,0 @@
surface thing:surface:provider.stack.stack viewport 800x600 scale 1 pixels
root 0 0 800 168
std-stat 2 2 796 36
std-stat/stat-label 2 2 796 16
std-stat/stat-value 2 22 796 16
outer-card 2 46 796 120
outer-card/card-title 4 48 792 16
outer-card/card-act 4 72 792 16
outer-card/card-act-label 4 72 32 16
inner-card 4 96 792 68
inner-card/card-title 6 98 788 16
inner-card/card-act 6 122 788 16
inner-card/card-act-label 6 122 32 16
inner-note 6 146 788 16

View file

@ -1,8 +0,0 @@
surface thing:surface:provider.hostile.duplicate-id refused DuplicateNodeId
surface thing:surface:provider.hostile.schema-mismatch viewport 800x600 scale 1 pixels
root 0 0 800 20
mismatch 2 2 796 16
surface thing:surface:provider.hostile.undeclared-command refused UndeclaredCommand
surface thing:surface:provider.hostile.unresolved-use viewport 800x600 scale 1 pixels
root 0 0 800 20
ghost-use 2 2 796 16

View file

@ -1,85 +0,0 @@
surface thing:surface:provider.deep.deep viewport 800x600 scale 1 pixels
deep-0 0 0 800 336
deep-1 2 2 796 332
deep-2 4 4 792 328
deep-3 6 6 788 324
deep-4 8 8 784 320
deep-5 10 10 780 316
deep-6 12 12 776 312
deep-7 14 14 772 308
deep-8 16 16 768 304
deep-9 18 18 764 300
deep-10 20 20 760 296
deep-11 22 22 756 292
deep-12 24 24 752 288
deep-13 26 26 748 284
deep-14 28 28 744 280
deep-15 30 30 740 276
deep-16 32 32 736 272
deep-17 34 34 732 268
deep-18 36 36 728 264
deep-19 38 38 724 260
deep-20 40 40 720 256
deep-21 42 42 716 252
deep-22 44 44 712 248
deep-23 46 46 708 244
deep-24 48 48 704 240
deep-25 50 50 700 236
deep-26 52 52 696 232
deep-27 54 54 692 228
deep-28 56 56 688 224
deep-29 58 58 684 220
deep-30 60 60 680 216
deep-31 62 62 676 212
deep-32 64 64 672 208
deep-33 66 66 668 204
deep-34 68 68 664 200
deep-35 70 70 660 196
deep-36 72 72 656 192
deep-37 74 74 652 188
deep-38 76 76 648 184
deep-39 78 78 644 180
deep-40 80 80 640 176
deep-41 82 82 636 172
deep-42 84 84 632 168
deep-43 86 86 628 164
deep-44 88 88 624 160
deep-45 90 90 620 156
deep-46 92 92 616 152
deep-47 94 94 612 148
deep-48 96 96 608 144
deep-49 98 98 604 140
deep-50 100 100 600 136
deep-51 102 102 596 132
deep-52 104 104 592 128
deep-53 106 106 588 124
deep-54 108 108 584 120
deep-55 110 110 580 116
deep-56 112 112 576 112
deep-57 114 114 572 108
deep-58 116 116 568 104
deep-59 118 118 564 100
deep-60 120 120 560 96
deep-61 122 122 556 92
deep-62 124 124 552 88
deep-63 126 126 548 84
deep-64 128 128 544 80
deep-65 130 130 540 76
deep-66 132 132 536 72
deep-67 134 134 532 68
deep-68 136 136 528 64
deep-69 138 138 524 60
deep-70 140 140 520 56
deep-71 142 142 516 52
deep-72 144 144 512 48
deep-73 146 146 508 44
deep-74 148 148 504 40
deep-75 150 150 500 36
deep-76 152 152 496 32
deep-77 154 154 492 28
deep-78 156 156 488 24
deep-79 158 158 484 20
deep-80 160 160 480 16
deep-81 162 162 476 12
deep-82 164 164 472 8
deep-83 166 166 468 4

View file

@ -1,7 +0,0 @@
surface thing:surface:provider.text.text-edge viewport 800x600 scale 1.5 pixels
root 0 0 1200 342
bidi 3 3 1194 24
cjk 3 39 1194 24
combining 3 75 1194 24
emoji-zwj 3 111 1194 24
long-wrap 3 147 1194 192

View file

@ -1,7 +0,0 @@
surface thing:surface:provider.text.text-edge viewport 800x600 scale 1 pixels
root 0 0 800 228
bidi 2 2 796 16
cjk 2 26 796 16
combining 2 50 796 16
emoji-zwj 2 74 796 16
long-wrap 2 98 796 128

View file

@ -1,7 +0,0 @@
surface thing:surface:provider.swarm.dashboard viewport 100x37 scale 1 cells
fill 0 0 100 23 r8 #1e1e2eff
text 2 2 #ffffffff cells "42.0%" bold=false italic=false underline=false
text 54 2 #eeeef4ff cells "Eureka" bold=false italic=false underline=false
text 2 11 #eeeef4ff cells "Libby" bold=false italic=false underline=false
text 54 11 #eeeef4ff cells "Kiko" bold=false italic=false underline=false
text 2 20 #eeeef4ff cells "Restart" bold=false italic=false underline=false

View file

@ -1,7 +0,0 @@
surface thing:surface:provider.swarm.dashboard viewport 800x600 scale 1 pixels
fill 0 0 800 68 r8 #1e1e2eff
text 2 2 #ffffffff font0 size16 [52@0,0 50@8,0 46@16,0 48@24,0 37@32,0]
text 404 2 #eeeef4ff font0 size16 [69@0,0 117@8,0 114@16,0 101@24,0 107@32,0 97@40,0]
text 2 26 #eeeef4ff font0 size16 [76@0,0 105@8,0 98@16,0 98@24,0 121@32,0]
text 404 26 #eeeef4ff font0 size16 [75@0,0 105@8,0 107@16,0 111@24,0]
text 2 50 #eeeef4ff font0 size16 [82@0,0 101@8,0 115@16,0 116@24,0 97@32,0 114@40,0 116@48,0]

View file

@ -1,2 +0,0 @@
surface thing:surface:provider.login.login viewport 800x600 scale 1 pixels
text 2 34 #eeeef4ff font0 size16 [83@0,0 105@8,0 103@16,0 110@24,0 32@32,0 105@40,0 110@48,0]

View file

@ -1,2 +0,0 @@
surface thing:surface:provider.muninn.input-target viewport 800x600 scale 1 pixels
text 282 122 #eeeef4ff font0 size16 [82@0,0 101@8,0 97@16,0 100@24,0 121@32,0]

View file

@ -1 +0,0 @@
surface thing:surface:provider.settings.form viewport 800x600 scale 1 pixels

View file

@ -1,7 +0,0 @@
surface thing:surface:provider.dialog.modal viewport 800x600 scale 1.5 pixels
text 2 2 #eeeef4ff font0 size16 [84@0,0 104@8,0 101@16,0 32@24,0 97@32,0 114@40,0 99@48,0 104@56,0 105@64,0 118@72,0 101@80,0 32@88,0 104@96,0 111@104,0 108@112,0 100@120,0 115@128,0 32@136,0 49@144,0 50@152,0 32@160,0 105@168,0 116@176,0 101@184,0 109@192,0 115@200,0 46@208,0]
fill 0 0 800 600 r0 #00000099
fill 0 266 800 68 r6 #2c2c3eff
text 2 268 #eeeef4ff font0 size16 [68@0,0 101@8,0 108@16,0 101@24,0 116@32,0 101@40,0 32@48,0 116@56,0 104@64,0 101@72,0 32@80,0 97@88,0 114@96,0 99@104,0 104@112,0 105@120,0 118@128,0 101@136,0 63@144,0]
text 2 292 #eeeef4ff font0 size16 [68@0,0 101@8,0 108@16,0 101@24,0 116@32,0 101@40,0]
text 2 316 #eeeef4ff font0 size16 [67@0,0 97@8,0 110@16,0 99@24,0 101@32,0 108@40,0]

View file

@ -1,7 +0,0 @@
surface thing:surface:provider.dialog.modal viewport 800x600 scale 1 pixels
text 2 2 #eeeef4ff font0 size16 [84@0,0 104@8,0 101@16,0 32@24,0 97@32,0 114@40,0 99@48,0 104@56,0 105@64,0 118@72,0 101@80,0 32@88,0 104@96,0 111@104,0 108@112,0 100@120,0 115@128,0 32@136,0 49@144,0 50@152,0 32@160,0 105@168,0 116@176,0 101@184,0 109@192,0 115@200,0 46@208,0]
fill 0 0 800 600 r0 #00000099
fill 0 266 800 68 r6 #2c2c3eff
text 2 268 #eeeef4ff font0 size16 [68@0,0 101@8,0 108@16,0 101@24,0 116@32,0 101@40,0 32@48,0 116@56,0 104@64,0 101@72,0 32@80,0 97@88,0 114@96,0 99@104,0 104@112,0 105@120,0 118@128,0 101@136,0 63@144,0]
text 2 292 #eeeef4ff font0 size16 [68@0,0 101@8,0 108@16,0 101@24,0 116@32,0 101@40,0]
text 2 316 #eeeef4ff font0 size16 [67@0,0 97@8,0 110@16,0 99@24,0 101@32,0 108@40,0]

File diff suppressed because it is too large Load diff

View file

@ -1 +0,0 @@
surface thing:surface:provider.market.plot viewport 800x600 scale 1 pixels

View file

@ -1,4 +0,0 @@
surface thing:surface:provider.viewport.embed-viewport viewport 800x600 scale 1 pixels
text 2 2 #eeeef4ff font0 size16 [98@0,0 101@8,0 102@16,0 111@24,0 114@32,0 101@40,0]
embed 244 2 320 180 "viewport.world" "main"
text 758 2 #eeeef4ff font0 size16 [97@0,0 102@8,0 116@16,0 101@24,0 114@32,0]

View file

@ -1,8 +0,0 @@
surface thing:surface:provider.stack.stack viewport 800x600 scale 1 pixels
text 2 2 #ff00ffff font0 size16 [76@0,0 111@8,0 97@16,0 100@24,0]
text 4 48 #ffffffff font0 size16 [67@0,0 97@8,0 114@16,0 100@24,0]
text 4 72 #eeeef4ff font0 size16 [79@0,0 112@8,0 101@16,0 110@24,0]
text 6 98 #ffffffff font0 size16 [67@0,0 97@8,0 114@16,0 100@24,0]
text 6 122 #eeeef4ff font0 size16 [79@0,0 112@8,0 101@16,0 110@24,0]
text 6 146 #eeeef4ff font0 size16 [110@0,0 101@8,0 115@16,0 116@24,0 101@32,0 100@40,0]
diagnostic ThemeTokenUnknown std-stat/stat-label caption

View file

@ -1,7 +0,0 @@
surface thing:surface:provider.hostile.duplicate-id refused DuplicateNodeId
surface thing:surface:provider.hostile.schema-mismatch viewport 800x600 scale 1 pixels
stroke 2 2 796 16 r0 w1 #e5484dff
surface thing:surface:provider.hostile.undeclared-command refused UndeclaredCommand
surface thing:surface:provider.hostile.unresolved-use viewport 800x600 scale 1 pixels
fill 2 2 796 16 r0 #6e6e80ff
stroke 2 2 796 16 r0 w1 #e5484dff

View file

@ -1 +0,0 @@
surface thing:surface:provider.deep.deep viewport 800x600 scale 1 pixels

View file

@ -1,13 +0,0 @@
surface thing:surface:provider.text.text-edge viewport 800x600 scale 1 pixels
text 2 2 #eeeef4ff font0 size16 [72@0,0 101@8,0 108@16,0 108@24,0 111@32,0 32@40,0 1513@48,0 1500@56,0 1493@64,0 1501@72,0 32@80,0 1506@88,0 1493@96,0 1500@104,0 1501@112,0 32@120,0 97@128,0 110@136,0 100@144,0 32@152,0 1605@160,0 1585@168,0 1581@176,0 1576@184,0 1575@192,0 32@200,0 1576@208,0 1575@216,0 1604@224,0 1593@232,0 1575@240,0 1604@248,0 1605@256,0 32@264,0 116@272,0 104@280,0 101@288,0 110@296,0 32@304,0 49@312,0 50@320,0 51@328,0 32@336,0 101@344,0 110@352,0 100@360,0 46@368,0]
text 2 26 #eeeef4ff font0 size16 [26085@0,0 26412@8,0 35486@16,0 12486@24,0 12473@32,0 12488@40,0 32@48,0 20320@56,0 22909@64,0 19990@72,0 30028@80,0 32@88,0 54620@96,0 44397@104,0 50612@112,0 32@120,0 65313@128,0 65314@136,0 65315@144,0 65297@152,0 65298@160,0 65299@168,0]
text 2 50 #eeeef4ff font0 size16 [101@0,0 769@8,0 32@16,0 97@24,0 776@32,0 32@40,0 110@48,0 771@56,0 32@64,0 111@72,0 770@80,0 803@88,0 32@96,0 122@104,0 859@112,0 847@120,0 768@128,0]
text 2 74 #eeeef4ff font0 size16 [128105@0,0 8205@8,0 128105@16,0 8205@24,0 128103@32,0 8205@40,0 128102@48,0 32@56,0 128104@64,0 127997@72,0 8205@80,0 128187@88,0 32@96,0 127987@104,0 65039@112,0 8205@120,0 127752@128,0]
text 2 98 #eeeef4ff font0 size16 [84@0,0 104@8,0 101@16,0 32@24,0 113@32,0 117@40,0 105@48,0 99@56,0 107@64,0 32@72,0 98@80,0 114@88,0 111@96,0 119@104,0 110@112,0 32@120,0 102@128,0 111@136,0 120@144,0 32@152,0 106@160,0 117@168,0 109@176,0 112@184,0 115@192,0 32@200,0 111@208,0 118@216,0 101@224,0 114@232,0 32@240,0 116@248,0 104@256,0 101@264,0 32@272,0 108@280,0 97@288,0 122@296,0 121@304,0 32@312,0 100@320,0 111@328,0 103@336,0 32@344,0 119@352,0 104@360,0 105@368,0 108@376,0 101@384,0 32@392,0 116@400,0 104@408,0 101@416,0 32@424,0 101@432,0 118@440,0 101@448,0 110@456,0 105@464,0 110@472,0 103@480,0 32@488,0 108@496,0 105@504,0 103@512,0 104@520,0 116@528,0 32@536,0 115@544,0 108@552,0 105@560,0 100@568,0 101@576,0 115@584,0 32@592,0 97@600,0 99@608,0 114@616,0 111@624,0 115@632,0 115@640,0 32@648,0 116@656,0 104@664,0 101@672,0 32@680,0 118@688,0 97@696,0 108@704,0 108@712,0 101@720,0 121@728,0 44@736,0 32@744,0 97@752,0 110@760,0 100@768,0 32@776,0 116@784,0]
text 2 114 #eeeef4ff font0 size16 [104@0,0 101@8,0 32@16,0 108@24,0 111@32,0 110@40,0 103@48,0 32@56,0 112@64,0 97@72,0 114@80,0 97@88,0 103@96,0 114@104,0 97@112,0 112@120,0 104@128,0 32@136,0 107@144,0 101@152,0 101@160,0 112@168,0 115@176,0 32@184,0 103@192,0 111@200,0 105@208,0 110@216,0 103@224,0 32@232,0 115@240,0 111@248,0 32@256,0 116@264,0 104@272,0 97@280,0 116@288,0 32@296,0 97@304,0 110@312,0 121@320,0 32@328,0 114@336,0 101@344,0 97@352,0 115@360,0 111@368,0 110@376,0 97@384,0 98@392,0 108@400,0 101@408,0 32@416,0 99@424,0 111@432,0 108@440,0 117@448,0 109@456,0 110@464,0 32@472,0 109@480,0 117@488,0 115@496,0 116@504,0 32@512,0 98@520,0 114@528,0 101@536,0 97@544,0 107@552,0 32@560,0 105@568,0 116@576,0 32@584,0 97@592,0 99@600,0 114@608,0 111@616,0 115@624,0 115@632,0 32@640,0 115@648,0 101@656,0 118@664,0 101@672,0 114@680,0 97@688,0 108@696,0 32@704,0 108@712,0 105@720,0 110@728,0 101@736,0 115@744,0 46@752,0 32@760,0 84@768,0 104@776,0 101@784,0]
text 2 130 #eeeef4ff font0 size16 [32@0,0 113@8,0 117@16,0 105@24,0 99@32,0 107@40,0 32@48,0 98@56,0 114@64,0 111@72,0 119@80,0 110@88,0 32@96,0 102@104,0 111@112,0 120@120,0 32@128,0 106@136,0 117@144,0 109@152,0 112@160,0 115@168,0 32@176,0 111@184,0 118@192,0 101@200,0 114@208,0 32@216,0 116@224,0 104@232,0 101@240,0 32@248,0 108@256,0 97@264,0 122@272,0 121@280,0 32@288,0 100@296,0 111@304,0 103@312,0 32@320,0 119@328,0 104@336,0 105@344,0 108@352,0 101@360,0 32@368,0 116@376,0 104@384,0 101@392,0 32@400,0 101@408,0 118@416,0 101@424,0 110@432,0 105@440,0 110@448,0 103@456,0 32@464,0 108@472,0 105@480,0 103@488,0 104@496,0 116@504,0 32@512,0 115@520,0 108@528,0 105@536,0 100@544,0 101@552,0 115@560,0 32@568,0 97@576,0 99@584,0 114@592,0 111@600,0 115@608,0 115@616,0 32@624,0 116@632,0 104@640,0 101@648,0 32@656,0 118@664,0 97@672,0 108@680,0 108@688,0 101@696,0 121@704,0 44@712,0 32@720,0 97@728,0 110@736,0 100@744,0 32@752,0 116@760,0 104@768,0 101@776,0 32@784,0]
text 2 146 #eeeef4ff font0 size16 [108@0,0 111@8,0 110@16,0 103@24,0 32@32,0 112@40,0 97@48,0 114@56,0 97@64,0 103@72,0 114@80,0 97@88,0 112@96,0 104@104,0 32@112,0 107@120,0 101@128,0 101@136,0 112@144,0 115@152,0 32@160,0 103@168,0 111@176,0 105@184,0 110@192,0 103@200,0 32@208,0 115@216,0 111@224,0 32@232,0 116@240,0 104@248,0 97@256,0 116@264,0 32@272,0 97@280,0 110@288,0 121@296,0 32@304,0 114@312,0 101@320,0 97@328,0 115@336,0 111@344,0 110@352,0 97@360,0 98@368,0 108@376,0 101@384,0 32@392,0 99@400,0 111@408,0 108@416,0 117@424,0 109@432,0 110@440,0 32@448,0 109@456,0 117@464,0 115@472,0 116@480,0 32@488,0 98@496,0 114@504,0 101@512,0 97@520,0 107@528,0 32@536,0 105@544,0 116@552,0 32@560,0 97@568,0 99@576,0 114@584,0 111@592,0 115@600,0 115@608,0 32@616,0 115@624,0 101@632,0 118@640,0 101@648,0 114@656,0 97@664,0 108@672,0 32@680,0 108@688,0 105@696,0 110@704,0 101@712,0 115@720,0 46@728,0 32@736,0 84@744,0 104@752,0 101@760,0 32@768,0 113@776,0 117@784,0]
text 2 162 #eeeef4ff font0 size16 [105@0,0 99@8,0 107@16,0 32@24,0 98@32,0 114@40,0 111@48,0 119@56,0 110@64,0 32@72,0 102@80,0 111@88,0 120@96,0 32@104,0 106@112,0 117@120,0 109@128,0 112@136,0 115@144,0 32@152,0 111@160,0 118@168,0 101@176,0 114@184,0 32@192,0 116@200,0 104@208,0 101@216,0 32@224,0 108@232,0 97@240,0 122@248,0 121@256,0 32@264,0 100@272,0 111@280,0 103@288,0 32@296,0 119@304,0 104@312,0 105@320,0 108@328,0 101@336,0 32@344,0 116@352,0 104@360,0 101@368,0 32@376,0 101@384,0 118@392,0 101@400,0 110@408,0 105@416,0 110@424,0 103@432,0 32@440,0 108@448,0 105@456,0 103@464,0 104@472,0 116@480,0 32@488,0 115@496,0 108@504,0 105@512,0 100@520,0 101@528,0 115@536,0 32@544,0 97@552,0 99@560,0 114@568,0 111@576,0 115@584,0 115@592,0 32@600,0 116@608,0 104@616,0 101@624,0 32@632,0 118@640,0 97@648,0 108@656,0 108@664,0 101@672,0 121@680,0 44@688,0 32@696,0 97@704,0 110@712,0 100@720,0 32@728,0 116@736,0 104@744,0 101@752,0 32@760,0 108@768,0 111@776,0 110@784,0]
text 2 178 #eeeef4ff font0 size16 [103@0,0 32@8,0 112@16,0 97@24,0 114@32,0 97@40,0 103@48,0 114@56,0 97@64,0 112@72,0 104@80,0 32@88,0 107@96,0 101@104,0 101@112,0 112@120,0 115@128,0 32@136,0 103@144,0 111@152,0 105@160,0 110@168,0 103@176,0 32@184,0 115@192,0 111@200,0 32@208,0 116@216,0 104@224,0 97@232,0 116@240,0 32@248,0 97@256,0 110@264,0 121@272,0 32@280,0 114@288,0 101@296,0 97@304,0 115@312,0 111@320,0 110@328,0 97@336,0 98@344,0 108@352,0 101@360,0 32@368,0 99@376,0 111@384,0 108@392,0 117@400,0 109@408,0 110@416,0 32@424,0 109@432,0 117@440,0 115@448,0 116@456,0 32@464,0 98@472,0 114@480,0 101@488,0 97@496,0 107@504,0 32@512,0 105@520,0 116@528,0 32@536,0 97@544,0 99@552,0 114@560,0 111@568,0 115@576,0 115@584,0 32@592,0 115@600,0 101@608,0 118@616,0 101@624,0 114@632,0 97@640,0 108@648,0 32@656,0 108@664,0 105@672,0 110@680,0 101@688,0 115@696,0 46@704,0 32@712,0 84@720,0 104@728,0 101@736,0 32@744,0 113@752,0 117@760,0 105@768,0 99@776,0 107@784,0]
text 2 194 #eeeef4ff font0 size16 [32@0,0 98@8,0 114@16,0 111@24,0 119@32,0 110@40,0 32@48,0 102@56,0 111@64,0 120@72,0 32@80,0 106@88,0 117@96,0 109@104,0 112@112,0 115@120,0 32@128,0 111@136,0 118@144,0 101@152,0 114@160,0 32@168,0 116@176,0 104@184,0 101@192,0 32@200,0 108@208,0 97@216,0 122@224,0 121@232,0 32@240,0 100@248,0 111@256,0 103@264,0 32@272,0 119@280,0 104@288,0 105@296,0 108@304,0 101@312,0 32@320,0 116@328,0 104@336,0 101@344,0 32@352,0 101@360,0 118@368,0 101@376,0 110@384,0 105@392,0 110@400,0 103@408,0 32@416,0 108@424,0 105@432,0 103@440,0 104@448,0 116@456,0 32@464,0 115@472,0 108@480,0 105@488,0 100@496,0 101@504,0 115@512,0 32@520,0 97@528,0 99@536,0 114@544,0 111@552,0 115@560,0 115@568,0 32@576,0 116@584,0 104@592,0 101@600,0 32@608,0 118@616,0 97@624,0 108@632,0 108@640,0 101@648,0 121@656,0 44@664,0 32@672,0 97@680,0 110@688,0 100@696,0 32@704,0 116@712,0 104@720,0 101@728,0 32@736,0 108@744,0 111@752,0 110@760,0 103@768,0 32@776,0 112@784,0]
text 2 210 #eeeef4ff font0 size16 [97@0,0 114@8,0 97@16,0 103@24,0 114@32,0 97@40,0 112@48,0 104@56,0 32@64,0 107@72,0 101@80,0 101@88,0 112@96,0 115@104,0 32@112,0 103@120,0 111@128,0 105@136,0 110@144,0 103@152,0 32@160,0 115@168,0 111@176,0 32@184,0 116@192,0 104@200,0 97@208,0 116@216,0 32@224,0 97@232,0 110@240,0 121@248,0 32@256,0 114@264,0 101@272,0 97@280,0 115@288,0 111@296,0 110@304,0 97@312,0 98@320,0 108@328,0 101@336,0 32@344,0 99@352,0 111@360,0 108@368,0 117@376,0 109@384,0 110@392,0 32@400,0 109@408,0 117@416,0 115@424,0 116@432,0 32@440,0 98@448,0 114@456,0 101@464,0 97@472,0 107@480,0 32@488,0 105@496,0 116@504,0 32@512,0 97@520,0 99@528,0 114@536,0 111@544,0 115@552,0 115@560,0 32@568,0 115@576,0 101@584,0 118@592,0 101@600,0 114@608,0 97@616,0 108@624,0 32@632,0 108@640,0 105@648,0 110@656,0 101@664,0 115@672,0 46@680,0 32@688,0]

View file

@ -1,864 +0,0 @@
SurfaceDocument {
provider_id: ProviderId(
"provider.stack",
),
label: Segment(
"stack",
),
version: Version(
1,
),
title: "Stack",
root: Box(
BoxNode {
common: NodeCommon {
id: NodeId(
"root",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
style: BoxStyle {
display: Flex,
direction: Column,
wrap: NoWrap,
gap: Size2 {
width: Px(
Scalar {
value: 4.0,
},
),
height: Px(
Scalar {
value: 8.0,
},
),
},
padding: Edges {
top: Px(
Scalar {
value: 2.0,
},
),
right: Px(
Scalar {
value: 2.0,
},
),
bottom: Px(
Scalar {
value: 2.0,
},
),
left: Px(
Scalar {
value: 2.0,
},
),
},
margin: Edges {
top: Auto,
right: Auto,
bottom: Auto,
left: Auto,
},
size: Size2 {
width: Percent(
Scalar {
value: 100.0,
},
),
height: Content,
},
min_size: Size2 {
width: Px(
Scalar {
value: 0.0,
},
),
height: Px(
Scalar {
value: 0.0,
},
),
},
max_size: Size2 {
width: Auto,
height: Auto,
},
position: Relative,
inset: Edges {
top: Auto,
right: Auto,
bottom: Auto,
left: Auto,
},
overflow: Visible,
align_items: Stretch,
align_self: Auto,
align_content: Start,
justify_content: SpaceBetween,
grow: 1.0,
shrink: 0.0,
basis: Auto,
grid_columns: [],
grid_rows: [],
},
paint: Paint {
background: None,
border: None,
radius: 0.0,
},
role: Group,
children: [
Box(
BoxNode {
common: NodeCommon {
id: NodeId(
"std-stat",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
style: BoxStyle {
display: Flex,
direction: Column,
wrap: NoWrap,
gap: Size2 {
width: Px(
Scalar {
value: 0.0,
},
),
height: Px(
Scalar {
value: 4.0,
},
),
},
padding: Edges {
top: Px(
Scalar {
value: 0.0,
},
),
right: Px(
Scalar {
value: 0.0,
},
),
bottom: Px(
Scalar {
value: 0.0,
},
),
left: Px(
Scalar {
value: 0.0,
},
),
},
margin: Edges {
top: Px(
Scalar {
value: 0.0,
},
),
right: Px(
Scalar {
value: 0.0,
},
),
bottom: Px(
Scalar {
value: 0.0,
},
),
left: Px(
Scalar {
value: 0.0,
},
),
},
size: Size2 {
width: Auto,
height: Content,
},
min_size: Size2 {
width: Px(
Scalar {
value: 0.0,
},
),
height: Px(
Scalar {
value: 0.0,
},
),
},
max_size: Size2 {
width: Auto,
height: Auto,
},
position: Relative,
inset: Edges {
top: Auto,
right: Auto,
bottom: Auto,
left: Auto,
},
overflow: Visible,
align_items: Stretch,
align_self: Auto,
align_content: Start,
justify_content: Start,
grow: 0.0,
shrink: 1.0,
basis: Auto,
grid_columns: [],
grid_rows: [],
},
paint: Paint {
background: None,
border: None,
radius: 0.0,
},
role: Group,
children: [
Text(
TextNode {
common: NodeCommon {
id: NodeId(
"std-stat/stat-label",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
content: Literal(
TextLiteral {
value: "Load",
},
),
style_token: "caption",
wrap: true,
max_lines: None,
selectable: false,
},
),
Text(
TextNode {
common: NodeCommon {
id: NodeId(
"std-stat/stat-value",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
content: Bound(
Bind {
source: Record(
StateRef {
provider: Some(
ProviderId(
"provider.swarm",
),
),
schema: SchemaId(
"gamecult.thing.test.swarm.v1",
),
key: RecordKey(
"summary",
),
},
),
member: MemberPath {
steps: [
Name(
MemberName {
name: "Load",
},
),
],
},
format: None,
},
),
style_token: "title",
wrap: true,
max_lines: None,
selectable: false,
},
),
],
},
),
Box(
BoxNode {
common: NodeCommon {
id: NodeId(
"outer-card",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
style: BoxStyle {
display: Flex,
direction: Column,
wrap: NoWrap,
gap: Size2 {
width: Px(
Scalar {
value: 4.0,
},
),
height: Px(
Scalar {
value: 8.0,
},
),
},
padding: Edges {
top: Px(
Scalar {
value: 2.0,
},
),
right: Px(
Scalar {
value: 2.0,
},
),
bottom: Px(
Scalar {
value: 2.0,
},
),
left: Px(
Scalar {
value: 2.0,
},
),
},
margin: Edges {
top: Auto,
right: Auto,
bottom: Auto,
left: Auto,
},
size: Size2 {
width: Percent(
Scalar {
value: 100.0,
},
),
height: Content,
},
min_size: Size2 {
width: Px(
Scalar {
value: 0.0,
},
),
height: Px(
Scalar {
value: 0.0,
},
),
},
max_size: Size2 {
width: Auto,
height: Auto,
},
position: Relative,
inset: Edges {
top: Auto,
right: Auto,
bottom: Auto,
left: Auto,
},
overflow: Visible,
align_items: Stretch,
align_self: Auto,
align_content: Start,
justify_content: SpaceBetween,
grow: 1.0,
shrink: 0.0,
basis: Auto,
grid_columns: [],
grid_rows: [],
},
paint: Paint {
background: None,
border: None,
radius: 0.0,
},
role: Group,
children: [
Text(
TextNode {
common: NodeCommon {
id: NodeId(
"outer-card/card-title",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
content: Literal(
TextLiteral {
value: "Card",
},
),
style_token: "title",
wrap: true,
max_lines: None,
selectable: false,
},
),
Repeat(
RepeatNode {
common: NodeCommon {
id: NodeId(
"outer-card/card-rows",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
collection: Records(
RecordsSource {
provider: Some(
ProviderId(
"provider.stack",
),
),
schema: SchemaId(
"gamecult.thing.test.swarm.v1",
),
key_prefix: "mind-",
},
),
key_member: MemberPath {
steps: [
Name(
MemberName {
name: "Id",
},
),
],
},
template: Text(
TextNode {
common: NodeCommon {
id: NodeId(
"outer-card/card-row",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
content: Bound(
Bind {
source: Item,
member: MemberPath {
steps: [
Name(
MemberName {
name: "Name",
},
),
],
},
format: None,
},
),
style_token: "body",
wrap: false,
max_lines: None,
selectable: false,
},
),
},
),
Button(
ButtonNode {
common: NodeCommon {
id: NodeId(
"outer-card/card-act",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
content: [
Text(
TextNode {
common: NodeCommon {
id: NodeId(
"outer-card/card-act-label",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
content: Literal(
TextLiteral {
value: "Open",
},
),
style_token: "body",
wrap: true,
max_lines: None,
selectable: false,
},
),
],
on_activate: Id(
CommandIdRef {
id: CommandId(
"open",
),
},
),
enabled: Literal(
BoolLiteral {
value: true,
},
),
},
),
Box(
BoxNode {
common: NodeCommon {
id: NodeId(
"inner-card",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
style: BoxStyle {
display: Flex,
direction: Column,
wrap: NoWrap,
gap: Size2 {
width: Px(
Scalar {
value: 4.0,
},
),
height: Px(
Scalar {
value: 8.0,
},
),
},
padding: Edges {
top: Px(
Scalar {
value: 2.0,
},
),
right: Px(
Scalar {
value: 2.0,
},
),
bottom: Px(
Scalar {
value: 2.0,
},
),
left: Px(
Scalar {
value: 2.0,
},
),
},
margin: Edges {
top: Auto,
right: Auto,
bottom: Auto,
left: Auto,
},
size: Size2 {
width: Percent(
Scalar {
value: 100.0,
},
),
height: Content,
},
min_size: Size2 {
width: Px(
Scalar {
value: 0.0,
},
),
height: Px(
Scalar {
value: 0.0,
},
),
},
max_size: Size2 {
width: Auto,
height: Auto,
},
position: Relative,
inset: Edges {
top: Auto,
right: Auto,
bottom: Auto,
left: Auto,
},
overflow: Visible,
align_items: Stretch,
align_self: Auto,
align_content: Start,
justify_content: SpaceBetween,
grow: 1.0,
shrink: 0.0,
basis: Auto,
grid_columns: [],
grid_rows: [],
},
paint: Paint {
background: None,
border: None,
radius: 0.0,
},
role: Group,
children: [
Text(
TextNode {
common: NodeCommon {
id: NodeId(
"inner-card/card-title",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
content: Literal(
TextLiteral {
value: "Card",
},
),
style_token: "title",
wrap: true,
max_lines: None,
selectable: false,
},
),
Repeat(
RepeatNode {
common: NodeCommon {
id: NodeId(
"inner-card/card-rows",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
collection: Records(
RecordsSource {
provider: Some(
ProviderId(
"provider.stack",
),
),
schema: SchemaId(
"gamecult.thing.test.swarm.v1",
),
key_prefix: "mind-",
},
),
key_member: MemberPath {
steps: [
Name(
MemberName {
name: "Id",
},
),
],
},
template: Text(
TextNode {
common: NodeCommon {
id: NodeId(
"inner-card/card-row",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
content: Bound(
Bind {
source: Item,
member: MemberPath {
steps: [
Name(
MemberName {
name: "Name",
},
),
],
},
format: None,
},
),
style_token: "body",
wrap: false,
max_lines: None,
selectable: false,
},
),
},
),
Button(
ButtonNode {
common: NodeCommon {
id: NodeId(
"inner-card/card-act",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
content: [
Text(
TextNode {
common: NodeCommon {
id: NodeId(
"inner-card/card-act-label",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
content: Literal(
TextLiteral {
value: "Open",
},
),
style_token: "body",
wrap: true,
max_lines: None,
selectable: false,
},
),
],
on_activate: Id(
CommandIdRef {
id: CommandId(
"open",
),
},
),
enabled: Literal(
BoolLiteral {
value: true,
},
),
},
),
Text(
TextNode {
common: NodeCommon {
id: NodeId(
"inner-note",
),
visible: Literal(
BoolLiteral {
value: true,
},
),
a11y_label: None,
},
content: Literal(
TextLiteral {
value: "nested",
},
),
style_token: "body",
wrap: true,
max_lines: None,
selectable: false,
},
),
],
},
),
],
},
),
],
},
),
commands: [
CommandDecl {
id: CommandId(
"open",
),
payload_schema: SchemaId(
"gamecult.thing.test.open.v1",
),
captures: [],
confirm: None,
},
],
}

View file

@ -1,288 +0,0 @@
//! The Resolver: the version rule (M9), the last good tree (M4), a late composition and the
//! interests that follow what the held trees read.
use thing_contract::*;
use thing_core::diagnostic::{Code, Diagnostic};
use thing_core::port::{Address, Change, Entry, Interest, Ledger, Record, Refusal, StatePort, SubscriptionId};
use thing_core::resolve::{Limits, Resolver};
use thing_testkit::build::*;
use thing_testkit::mem_state::{Call, MemState};
const PUB: &str = "pub.t";
const PROVIDER: &str = "provider.t";
struct Rig {
state: MemState,
resolver: Resolver,
ledger: Ledger,
}
fn command_button(id: &str, command_id: &str) -> Node {
Node::Button(ButtonNode { common: common(id), content: vec![], on_activate: command(command_id), enabled: lit_bool(true) })
}
fn surface(label: &str, version: i64, children: Vec<Node>) -> SurfaceDocument {
SurfaceDocument {
provider_id: ProviderId::new(PROVIDER),
label: seg(label),
version: ver(version),
title: format!("{label} v{version}"),
root: boxed("root", children),
commands: vec![],
}
}
fn reference(name: &str) -> CompositionRef {
CompositionRef { publisher: PUB.into(), name: seg(name), version: ver(1) }
}
fn use_of(id: &str, name: &str) -> Node {
Node::Use(UseNode { common: common(id), composition: reference(name), args: vec![] })
}
fn composition(name: &str, body_text: &str) -> CompositionDocument {
CompositionDocument { publisher: PUB.into(), name: seg(name), version: ver(1), params: vec![], body: text(&format!("{name}-body"), body_text) }
}
fn comp_address(name: &str) -> Address {
Address { provider: ProviderId::new(PUB), schema: SchemaId::new(CompositionDocument::SCHEMA_NAME), key: RecordKey::new(reference(name).record_key()) }
}
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(diagnostics: &[Diagnostic]) -> Vec<Code> {
diagnostics.iter().map(|diagnostic| diagnostic.code).collect()
}
impl Rig {
fn new() -> Self {
Self { state: MemState::new(), resolver: Resolver::new(Limits::default()), ledger: Ledger::new() }
}
fn apply(&mut self, change: Change) -> Vec<Diagnostic> {
self.resolver.apply(&change, &mut self.state, &mut self.ledger)
}
fn offer(&mut self, document: &SurfaceDocument) -> Vec<Diagnostic> {
self.apply(Change::Upsert(Entry { address: surface_address(document), record: Record::Surface(document.clone()) }))
}
fn put(&mut self, composition: &CompositionDocument) {
self.state.put(&ProviderId::new(PUB), composition);
}
/// Drain the port and apply each change, as the frame owner does.
fn settle(&mut self) -> Vec<Diagnostic> {
let mut diagnostics = Vec::new();
for change in self.state.drain() {
diagnostics.extend(self.apply(change));
}
diagnostics
}
fn title(&self, key: &str) -> Option<String> {
self.resolver.tree(key).map(|tree| tree.document().title.clone())
}
fn shows(&self, key: &str, node: &str) -> bool {
self.resolver.tree(key).is_some_and(|tree| format!("{:?}", tree.document().root).contains(node))
}
/// Subscribes and unsubscribes so far: a subscribe as its address, an unsubscribe as the address
/// that subscription was made for.
fn interest_calls(&self) -> Vec<(bool, Address)> {
let mut made: Vec<Address> = Vec::new();
let mut out = Vec::new();
for call in self.state.calls() {
match call {
Call::Subscribe(Interest::Record(address)) => {
made.push(address.clone());
out.push((true, address));
}
Call::Subscribe(other) => panic!("not a record interest: {other:?}"),
Call::Unsubscribe(SubscriptionId(id)) => out.push((false, made[id as usize].clone())),
_ => {}
}
}
out
}
}
#[test]
fn a_version_at_or_below_the_highest_offered_is_ignored_once() {
let mut rig = Rig::new();
let v1 = surface("main", 1, vec![]);
let key = v1.record_key();
assert!(rig.offer(&v1).is_empty());
assert_eq!(rig.title(&key).as_deref(), Some("main v1"));
// Equal and lower: one diagnostic per version however often offered; the tree stays.
let again = surface("main", 1, vec![boxed("other", vec![])]);
let below = surface("main", 0, vec![]);
assert_eq!(codes(&rig.offer(&again)), vec![Code::StaleVersionIgnored]);
assert!(rig.offer(&again).is_empty());
assert!(rig.offer(&v1).is_empty());
assert_eq!(codes(&rig.offer(&below)), vec![Code::StaleVersionIgnored]);
assert!(rig.offer(&below).is_empty());
assert_eq!(rig.title(&key).as_deref(), Some("main v1"));
assert!(!rig.shows(&key, "other"));
// A higher version replaces it.
assert!(rig.offer(&surface("main", 2, vec![])).is_empty());
assert_eq!(rig.title(&key).as_deref(), Some("main v2"));
}
#[test]
fn a_surface_that_fails_to_resolve_leaves_the_last_good_tree_displayed() {
let mut rig = Rig::new();
let v1 = surface("main", 1, vec![]);
let key = v1.record_key();
rig.offer(&v1);
let bad = surface("main", 2, vec![command_button("go", "undeclared")]);
assert_eq!(codes(&rig.offer(&bad)), vec![Code::UndeclaredCommand]);
assert_eq!(rig.title(&key).as_deref(), Some("main v1"));
// The refused version was offered: it is stale now, not tried again.
assert_eq!(codes(&rig.offer(&bad)), vec![Code::StaleVersionIgnored]);
assert_eq!(rig.title(&key).as_deref(), Some("main v1"));
assert!(rig.offer(&surface("main", 3, vec![])).is_empty());
assert_eq!(rig.title(&key).as_deref(), Some("main v3"));
}
#[test]
fn a_first_offer_that_fails_displays_nothing() {
let mut rig = Rig::new();
let bad = surface("main", 1, vec![command_button("go", "undeclared")]);
rig.offer(&bad);
assert!(rig.resolver.tree(&bad.record_key()).is_none());
}
#[test]
fn a_refused_surface_keeps_the_held_tree_and_is_not_a_delete() {
let mut rig = Rig::new();
let v1 = surface("main", 1, vec![]);
let key = v1.record_key();
rig.offer(&v1);
let address = surface_address(&v1);
let refusal = Refusal { kind: address.schema.clone(), address, detail: "unknown arm".into() };
let diagnostics = rig.apply(Change::Refused(refusal));
assert_eq!(codes(&diagnostics), vec![Code::DecodeRefused]);
assert_eq!(diagnostics[0].surface, key);
assert_eq!(rig.title(&key).as_deref(), Some("main v1"));
// The version it was refused at was never taken: the same version is still the highest.
assert_eq!(codes(&rig.offer(&v1)), vec![Code::StaleVersionIgnored]);
}
#[test]
fn a_composition_published_late_replaces_the_placeholder_without_a_republish() {
let mut rig = Rig::new();
let document = surface("main", 1, vec![use_of("ghost-use", "ghost")]);
let key = document.record_key();
assert_eq!(codes(&rig.offer(&document)), vec![Code::UnresolvedUse]);
assert!(!rig.shows(&key, "\"boo\""));
rig.put(&composition("ghost", "boo"));
assert!(rig.settle().is_empty());
assert!(rig.shows(&key, "\"boo\""));
// It goes away: the placeholder returns, and the interest stays.
rig.state.delete(&comp_address("ghost"));
assert_eq!(codes(&rig.settle()), vec![Code::UnresolvedUse]);
assert!(!rig.shows(&key, "\"boo\""));
// It comes back refused: a refusal is not absence.
rig.state.put_raw(comp_address("ghost"), vec![0xc1]);
assert_eq!(codes(&rig.settle()), vec![Code::DecodeRefused]);
assert_eq!(rig.interest_calls().len(), 1);
}
#[test]
fn interests_follow_what_the_held_trees_read() {
let mut rig = Rig::new();
let a1 = surface("a", 1, vec![use_of("u1", "one"), use_of("u2", "two")]);
let b1 = surface("b", 1, vec![use_of("u1", "one")]);
rig.put(&composition("one", "1"));
rig.put(&composition("two", "2"));
rig.offer(&a1);
rig.offer(&b1);
let (one, two) = (comp_address("one"), comp_address("two"));
// One subscription per address however many surfaces read it.
let held = rig.interest_calls();
assert_eq!(held.len(), 2);
assert!(held.contains(&(true, one.clone())) && held.contains(&(true, two.clone())));
// Changes and re-applies never resubscribe what is held.
rig.put(&composition("one", "1b"));
rig.settle();
rig.offer(&a1);
assert_eq!(rig.interest_calls().len(), 2);
// A new version that stops reading `two` lets it go; `one` is untouched.
rig.offer(&surface("a", 2, vec![use_of("u1", "one")]));
let mut expected = held.clone();
expected.push((false, two.clone()));
assert_eq!(rig.interest_calls(), expected);
// A shared address is released only when its last reader goes.
rig.apply(Change::Delete(surface_address(&a1)));
assert_eq!(rig.interest_calls().len(), 3);
rig.apply(Change::Delete(surface_address(&b1)));
assert_eq!(rig.interest_calls().last(), Some(&(false, one)));
assert_eq!(rig.interest_calls().len(), 4);
}
#[test]
fn a_surface_that_fails_still_holds_the_interests_it_read() {
let mut rig = Rig::new();
let bad = surface("main", 1, vec![use_of("ghost-use", "ghost"), command_button("go", "undeclared")]);
assert_eq!(codes(&rig.offer(&bad)), vec![Code::UnresolvedUse, Code::UndeclaredCommand]);
assert_eq!(rig.interest_calls(), vec![(true, comp_address("ghost"))]);
// No tree yet, still re-resolved when its composition arrives.
rig.put(&composition("ghost", "boo"));
assert_eq!(codes(&rig.settle()), vec![Code::UndeclaredCommand]);
assert!(rig.resolver.tree(&bad.record_key()).is_none());
}
#[test]
fn a_deleted_surface_keeps_its_version_as_a_tombstone() {
let rig_after_delete = || {
let mut rig = Rig::new();
rig.put(&composition("one", "1"));
let v3 = surface("main", 3, vec![use_of("u", "one")]);
rig.offer(&v3);
rig.apply(Change::Delete(surface_address(&v3)));
let key = v3.record_key();
assert!(rig.resolver.tree(&key).is_none());
// The tombstone holds no interest: the one subscription made is released.
let calls = rig.interest_calls();
assert_eq!(calls.len(), 2);
assert!(calls[0].0 && !calls[1].0);
(rig, key)
};
let (mut rig, key) = rig_after_delete();
assert_eq!(codes(&rig.offer(&surface("main", 1, vec![]))), vec![Code::StaleVersionIgnored]);
assert!(rig.resolver.tree(&key).is_none());
let (mut rig, key) = rig_after_delete();
assert_eq!(codes(&rig.offer(&surface("main", 3, vec![]))), vec![Code::StaleVersionIgnored]);
assert!(rig.resolver.tree(&key).is_none());
// A composition change does not bring a tombstone back.
rig.put(&composition("one", "1b"));
assert!(rig.settle().is_empty());
assert!(rig.resolver.tree(&key).is_none());
let (mut rig, key) = rig_after_delete();
assert!(rig.offer(&surface("main", 4, vec![])).is_empty());
assert_eq!(rig.title(&key).as_deref(), Some("main v4"));
}

File diff suppressed because it is too large Load diff

View file

@ -1,685 +0,0 @@
//! Render: the command list, clips, scroll, overlays, theme and the text seam. `THING_BLESS=1`
//! rewrites the `render-*` goldens through `golden::check`; any other run compares.
use std::path::PathBuf;
use thing_contract::*;
use thing_core::bind::{Binder, BoundTree};
use thing_core::diagnostic::Code;
use thing_core::layout::{LaidTree, LayoutFrame, Metrics, Run, layout};
use thing_core::port::Ledger;
use thing_core::render::{Placed, RenderCommand, RenderInput, Rendered, ScrollOffsets, balanced, clamp, render};
use thing_core::resolve::{Limits, resolve};
use thing_core::theme::Theme;
use thing_testkit::build::*;
use thing_testkit::fixture::Fixture;
use thing_testkit::golden;
use thing_testkit::mem_state::MemState;
use thing_testkit::measure::FixedMeasure;
use thing_testkit::state;
fn golden_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
}
fn frame(w: f32, h: f32, scale: f32, metrics: Metrics) -> LayoutFrame {
LayoutFrame { viewport: (w, h), scale, metrics }
}
fn pixels(scale: f32) -> LayoutFrame {
frame(800.0, 600.0, scale, Metrics::Pixels)
}
fn bind(state: &mut MemState, document: &SurfaceDocument) -> Result<BoundTree, Code> {
let limits = Limits::default();
let resolution = resolve(document, state, &limits);
let Some(tree) = resolution.tree else {
return Err(resolution.diagnostics.iter().find(|d| d.code.refuses_document()).map(|d| d.code).expect("a refusal"));
};
let mut binder = Binder::new(limits);
binder.bind(tree, state, &mut Ledger::new());
Ok(binder.tree(&document.record_key()).expect("bound").clone())
}
fn measure(frame: &LayoutFrame) -> FixedMeasure {
match frame.metrics {
Metrics::Pixels => FixedMeasure::pixels(),
Metrics::Cells => FixedMeasure::cells(),
}
}
fn input<'a>(frame: &LayoutFrame, scroll: &'a ScrollOffsets, theme: &'a Theme) -> RenderInput<'a> {
RenderInput { scale: frame.scale, metrics: frame.metrics, viewport: frame.viewport, scroll, theme }
}
fn draw(tree: &BoundTree, frame: &LayoutFrame, scroll: &ScrollOffsets) -> (LaidTree, Rendered) {
let laid = layout(tree, frame, &mut measure(frame)).unwrap();
let rendered = render(tree, &laid, &input(frame, scroll, &Theme::std()), &mut measure(frame));
(laid, rendered)
}
fn surface_of(root: Node) -> SurfaceDocument {
SurfaceDocument {
provider_id: ProviderId::new("provider.render"),
label: seg("inline"),
version: ver(1),
title: "inline".into(),
root,
commands: vec![CommandDecl { id: CommandId::new("dismiss"), payload_schema: SchemaId::new("gamecult.thing.test.dismiss.v1"), captures: vec![], confirm: None }],
}
}
fn inline(root: Node, frame: &LayoutFrame, scroll: &ScrollOffsets) -> (LaidTree, Rendered) {
let tree = bind(&mut MemState::new(), &surface_of(root)).expect("resolves");
draw(&tree, frame, scroll)
}
// ---- the text form -----------------------------------------------------------------------
fn hex(c: &Rgba) -> String {
format!("#{:02x}{:02x}{:02x}{:02x}", c.r, c.g, c.b, c.a)
}
fn rect_text(r: &thing_core::layout::Rect) -> String {
format!("{} {} {} {}", r.x, r.y, r.w, r.h)
}
fn points(points: &[(f32, f32)]) -> String {
points.iter().map(|(x, y)| format!("{x},{y}")).collect::<Vec<_>>().join(" ")
}
fn line(command: &RenderCommand) -> String {
match command {
RenderCommand::FillRect { rect, radius, color } => format!("fill {} r{radius} {}", rect_text(rect), hex(color)),
RenderCommand::StrokeRect { rect, radius, width, color } => format!("stroke {} r{radius} w{width} {}", rect_text(rect), hex(color)),
RenderCommand::Text { origin, run, color } => match run {
Run::Glyphs { font, size, glyphs } => {
let glyphs: Vec<String> = glyphs.iter().map(|g| format!("{}@{},{}", g.id, g.x, g.y)).collect();
format!("text {} {} {} font{} size{size} [{}]", origin.0, origin.1, hex(color), font.0, glyphs.join(" "))
}
Run::Cells { text, style } => format!(
"text {} {} {} cells {text:?} bold={} italic={} underline={}",
origin.0,
origin.1,
hex(color),
style.bold,
style.italic,
style.underline
),
},
RenderCommand::Image { rect, uri, alt } => format!("image {} {uri:?} {alt:?}", rect_text(rect)),
RenderCommand::ClipPush { rect, radius } => format!("clip-push {} r{radius}", rect_text(rect)),
RenderCommand::ClipPop => "clip-pop".to_string(),
RenderCommand::Polyline { points: p, width, color } => format!("polyline w{width} {} {}", hex(color), points(p)),
RenderCommand::Polygon { points: p, color } => format!("polygon {} {}", hex(color), points(p)),
RenderCommand::Embed { rect, slot_kind, slot_id } => format!("embed {} {slot_kind:?} {slot_id:?}", rect_text(rect)),
}
}
fn text_form(rendered: &Rendered) -> String {
let mut out = String::new();
for command in &rendered.commands {
out += &line(command);
out += "\n";
}
for d in &rendered.diagnostics {
out += &format!("diagnostic {:?} {} {}\n", d.code, d.node.as_ref().map_or("-", |n| n.as_str()), d.detail);
}
out
}
// ---- fixtures ----------------------------------------------------------------------------
/// Every surface of a fixture, bound under the fixture's state script and rendered.
fn fixture_runs(fixture: Fixture, frame: &LayoutFrame, scroll: &ScrollOffsets) -> Vec<(String, Result<Rendered, Code>)> {
let set = fixture.load();
let mut state = MemState::from_fixture(fixture);
state::script(fixture, &mut state);
set.surfaces
.iter()
.map(|document| (document.record_key(), bind(&mut state, document).map(|tree| draw(&tree, frame, scroll).1)))
.collect()
}
fn fixture_text(fixture: Fixture, frame: &LayoutFrame, scroll: &ScrollOffsets) -> String {
let mut out = String::new();
for (key, run) in fixture_runs(fixture, frame, scroll) {
match run {
Ok(rendered) => {
let mode = if frame.metrics == Metrics::Cells { "cells" } else { "pixels" };
out += &format!("surface {key} viewport {}x{} scale {} {mode}\n", frame.viewport.0, frame.viewport.1, frame.scale);
assert!(balanced(&rendered.commands), "{key}: clips are balanced");
out += &text_form(&rendered);
}
Err(code) => out += &format!("surface {key} refused {code:?}\n"),
}
}
out
}
fn stem(fixture: Fixture) -> String {
fixture.file_name().trim_end_matches(".surface.cc").to_string()
}
fn check(fixture: Fixture, suffix: &str, frame: &LayoutFrame, scroll: &ScrollOffsets) {
let text = fixture_text(fixture, frame, scroll);
golden::check(&golden_dir(), &format!("render-{}{suffix}.txt", stem(fixture)), text.as_bytes());
}
fn scrolled(node: &str, offset: (f32, f32)) -> ScrollOffsets {
let mut scroll = ScrollOffsets::default();
scroll.set(nid(node), offset);
scroll
}
#[test]
fn goldens() {
let none = ScrollOffsets::default();
for fixture in Fixture::ALL {
check(fixture, "", &pixels(1.0), &none);
}
check(Fixture::F01SwarmDashboard, "-cells", &frame(100.0, 37.0, 1.0, Metrics::Cells), &none);
check(Fixture::F05ModalOverlay, "-scale1.5", &pixels(1.5), &none);
check(Fixture::F06ScrollList, "-scale1.5", &pixels(1.5), &none);
check(Fixture::F06ScrollList, "-scroll1000", &pixels(1.0), &scrolled("root", (0.0, 1000.0)));
}
#[test]
fn determinism() {
let none = ScrollOffsets::default();
for fixture in Fixture::ALL {
for frame in [pixels(1.0), pixels(1.5), frame(100.0, 37.0, 1.0, Metrics::Cells)] {
let first = fixture_runs(fixture, &frame, &none);
let second = fixture_runs(fixture, &frame, &none);
let fresh = std::thread::spawn({
let none = none.clone();
move || fixture_runs(fixture, &frame, &none)
})
.join()
.unwrap();
assert_eq!(first, second, "{fixture:?} twice (a second bind of unchanged state included)");
assert_eq!(format!("{first:?}"), format!("{fresh:?}"), "{fixture:?} on a fresh thread");
}
}
}
// ---- inline trees ------------------------------------------------------------------------
fn plain() -> BoxStyle {
let zero = || px(0.0);
let auto = || size2(Dimension::Auto, Dimension::Auto);
BoxStyle {
display: Display::Flex,
direction: Direction::Row,
wrap: Wrap::NoWrap,
gap: size2(zero(), zero()),
padding: edges(zero()),
margin: edges(zero()),
size: auto(),
min_size: auto(),
max_size: auto(),
position: Position::Relative,
inset: edges(Dimension::Auto),
overflow: Overflow::Visible,
align_items: ItemAlign::Stretch,
align_self: ItemAlign::Auto,
align_content: ContentAlign::Auto,
justify_content: ContentAlign::Auto,
grow: 0.0,
shrink: 1.0,
basis: Dimension::Auto,
grid_columns: vec![],
grid_rows: vec![],
}
}
fn sized(w: f64, h: f64) -> BoxStyle {
BoxStyle { size: size2(px(w), px(h)), ..plain() }
}
fn bx(id: &str, style: BoxStyle, paint: Paint, children: Vec<Node>) -> Node {
Node::Box(BoxNode { common: common(id), style, paint, role: Role::Group, children })
}
fn flat(id: &str, style: BoxStyle, children: Vec<Node>) -> Node {
bx(id, style, plain_paint(), children)
}
fn filled(color: &str) -> Paint {
Paint { background: Some(ColorRef::Token(ThemeToken { name: color.into() })), border: None, radius: 0.0 }
}
fn embed(id: &str, w: f64, h: f64) -> Node {
Node::Embed(EmbedNode { common: common(id), slot_kind: "k".into(), slot_id: id.into(), width: w, height: h })
}
fn overlay(id: &str, anchor: Anchor, modal: bool, children: Vec<Node>) -> Node {
Node::Overlay(OverlayNode { common: common(id), anchor, modal, dismiss: command("dismiss"), children })
}
fn at(node: &str) -> Anchor {
Anchor::Node(AnchorNode { node: nid(node) })
}
fn placed<'a>(rendered: &'a Rendered, id: &str) -> &'a Placed {
rendered.placed.iter().find(|p| p.id.as_str() == id).unwrap_or_else(|| panic!("no node {id}"))
}
fn xywh(p: &Placed) -> (f32, f32, f32, f32) {
(p.rect.x, p.rect.y, p.rect.w, p.rect.h)
}
/// Clip depth after each command.
fn depths(commands: &[RenderCommand]) -> Vec<usize> {
let mut depth = 0usize;
commands
.iter()
.map(|c| {
match c {
RenderCommand::ClipPush { .. } => depth += 1,
RenderCommand::ClipPop => depth -= 1,
_ => {}
}
depth
})
.collect()
}
fn fills(rendered: &Rendered) -> Vec<(f32, f32, f32, f32)> {
rendered
.commands
.iter()
.filter_map(|c| match c {
RenderCommand::FillRect { rect, .. } => Some((rect.x, rect.y, rect.w, rect.h)),
_ => None,
})
.collect()
}
#[test]
fn balance_is_judged_on_the_sequence() {
let push = || RenderCommand::ClipPush { rect: thing_core::layout::Rect { x: 0.0, y: 0.0, w: 1.0, h: 1.0 }, radius: 0.0 };
assert!(balanced(&[]));
assert!(balanced(&[push(), push(), RenderCommand::ClipPop, RenderCommand::ClipPop]));
assert!(!balanced(&[push()]));
assert!(!balanced(&[RenderCommand::ClipPop]));
assert!(!balanced(&[RenderCommand::ClipPop, push()]));
assert!(!balanced(&[push(), RenderCommand::ClipPop, RenderCommand::ClipPop]));
}
#[test]
fn a_clip_closes_before_its_sibling_and_scrollbars_follow_it() {
let pane = |id: &str| flat(id, BoxStyle { overflow: Overflow::Clip, ..sized(50.0, 20.0) }, vec![embed(&format!("{id}-e"), 10.0, 10.0)]);
let root = flat("root", plain(), vec![pane("a"), pane("b")]);
let (_, rendered) = inline(root, &pixels(1.0), &ScrollOffsets::default());
let kinds: Vec<&str> = rendered
.commands
.iter()
.map(|c| match c {
RenderCommand::ClipPush { .. } => "push",
RenderCommand::ClipPop => "pop",
RenderCommand::Embed { .. } => "embed",
_ => "other",
})
.collect();
assert_eq!(kinds, ["push", "embed", "pop", "push", "embed", "pop"]);
}
#[test]
fn scroll_translates_descendants_and_never_the_scroll_node() {
let pane = bx("pane", BoxStyle { overflow: Overflow::Scroll, direction: Direction::Column, ..sized(100.0, 50.0) }, filled("thing.surface"), vec![
embed("top", 10.0, 30.0),
embed("mid", 10.0, 30.0),
embed("low", 10.0, 300.0),
]);
let root = flat("root", plain(), vec![pane]);
for scale in [1.0f32, 1.5] {
let frame = pixels(scale);
let (laid, at0) = inline(root.clone(), &frame, &ScrollOffsets::default());
let max = laid.nodes.iter().find(|n| n.id.as_str() == "pane").unwrap().max_scroll.unwrap();
assert!(max.1 > 100.0);
let device = 40.0;
let (_, moved) = inline(root.clone(), &frame, &scrolled("pane", (0.0, device)));
assert_eq!(xywh(placed(&moved, "pane")), xywh(placed(&at0, "pane")), "the scroll node stays");
for id in ["top", "mid", "low"] {
let (before, after) = (placed(&at0, id).rect, placed(&moved, id).rect);
assert!((after.y - (before.y - device / scale)).abs() < 1e-3, "{id} at scale {scale}");
assert_eq!((after.x, after.w, after.h), (before.x, before.w, before.h));
}
// Its background is the same fill, drawn first; the thumb is the one that moved.
assert_eq!(fills(&at0)[0], fills(&moved)[0]);
assert_ne!(fills(&at0)[1], fills(&moved)[1], "the thumb follows the offset");
// An offset past max_scroll clamps, and an absent or non-scroll id is ignored.
let (_, past) = inline(root.clone(), &frame, &scrolled("pane", (0.0, 1e9)));
let (_, exact) = inline(root.clone(), &frame, &scrolled("pane", (0.0, max.1)));
assert_eq!(past, exact);
let (_, other) = inline(root.clone(), &frame, &scrolled("nowhere", (0.0, 40.0)));
assert_eq!(other, at0);
let (_, neg) = inline(root.clone(), &frame, &scrolled("pane", (-50.0, -50.0)));
assert_eq!(neg, at0);
}
}
#[test]
fn a_row_scrolled_out_is_not_visible() {
let pane = flat("pane", BoxStyle { overflow: Overflow::Scroll, direction: Direction::Column, ..sized(100.0, 50.0) }, vec![
embed("top", 10.0, 30.0),
embed("mid", 10.0, 30.0),
embed("low", 10.0, 300.0),
]);
let root = flat("root", plain(), vec![pane]);
let (_, rendered) = inline(root, &pixels(1.0), &scrolled("pane", (0.0, 100.0)));
assert_eq!(placed(&rendered, "top").visible, None);
assert_eq!(placed(&rendered, "mid").visible, None);
assert!(placed(&rendered, "low").visible.is_some());
assert!(placed(&rendered, "pane").visible.is_some());
// Half in view: cut by the pane's padding box.
let (_, half) = inline(
flat("root", plain(), vec![flat("pane", BoxStyle { overflow: Overflow::Scroll, direction: Direction::Column, ..sized(100.0, 50.0) }, vec![embed("top", 10.0, 30.0), embed("low", 10.0, 300.0)])]),
&pixels(1.0),
&scrolled("pane", (0.0, 20.0)),
);
let visible = placed(&half, "top").visible.unwrap();
assert_eq!((visible.y, visible.h), (0.0, 10.0));
}
#[test]
fn clamp_holds_both_ends_and_refuses_nan() {
assert_eq!(clamp((5.0, 5.0), (10.0, 10.0)), (5.0, 5.0));
assert_eq!(clamp((-5.0, 50.0), (10.0, 10.0)), (0.0, 10.0));
assert_eq!(clamp((f32::NAN, f32::INFINITY), (10.0, 10.0)), (0.0, 10.0));
assert_eq!(clamp((5.0, 5.0), (0.0, f32::NAN)), (0.0, 0.0));
}
/// A scroll pane holding a target a popup is anchored to, with a popup inside the popup and a
/// popup on the viewport.
fn popup_tree() -> Node {
let pane = flat("pane", BoxStyle { overflow: Overflow::Scroll, direction: Direction::Column, ..sized(200.0, 100.0) }, vec![
embed("spacer", 10.0, 30.0),
bx("target", sized(50.0, 20.0), filled("thing.surface"), vec![]),
embed("tall", 10.0, 400.0),
]);
flat("root", plain(), vec![
pane,
overlay("pop", at("target"), false, vec![bx("pop-box", sized(20.0, 10.0), filled("thing.control.fill"), vec![])]),
overlay("deeper", at("pop-box"), false, vec![bx("deep-box", sized(5.0, 5.0), filled("thing.control.accent"), vec![])]),
overlay("fixed", Anchor::Viewport, false, vec![bx("fixed-box", sized(8.0, 8.0), filled("thing.control.accent"), vec![])]),
])
}
#[test]
fn an_overlay_anchored_in_a_scroll_box_follows_the_scroll_and_is_not_clipped() {
for scale in [1.0f32, 2.0] {
let frame = pixels(scale);
let (_, at0) = inline(popup_tree(), &frame, &ScrollOffsets::default());
let device = 20.0;
let (_, moved) = inline(popup_tree(), &frame, &scrolled("pane", (0.0, device)));
let up = device / scale;
for id in ["target", "pop", "pop-box", "deeper", "deep-box"] {
assert!((placed(&moved, id).rect.y - (placed(&at0, id).rect.y - up)).abs() < 1e-3, "{id} moves with the anchor's scroll ancestor at scale {scale}");
assert_eq!(placed(&moved, id).rect.x, placed(&at0, id).rect.x);
}
// The anchor's own scroll does not move the anchor: pop sits on target.
assert_eq!(xywh(placed(&moved, "pop")), xywh(placed(&moved, "target")));
// A viewport overlay does not move.
assert_eq!(xywh(placed(&moved, "fixed-box")), xywh(placed(&at0, "fixed-box")));
// Not clipped by the box: every clip is closed before the first overlay command.
let first = moved.commands.iter().position(|c| matches!(c, RenderCommand::FillRect { color, .. } if *color == Theme::std().color("thing.control.fill").unwrap())).unwrap();
assert_eq!(depths(&moved.commands)[first], 0);
assert!(balanced(&moved.commands));
assert!(placed(&moved, "pop-box").visible.is_some());
}
}
#[test]
fn overlays_paint_after_the_main_tree_and_the_scrim_precedes_its_content() {
let root = flat("root", plain(), vec![
overlay("modal", Anchor::Viewport, true, vec![bx("dialog", sized(40.0, 20.0), filled("thing.control.fill"), vec![])]),
bx("main", sized(30.0, 30.0), filled("thing.surface"), vec![]),
]);
let (_, rendered) = inline(root, &pixels(1.0), &ScrollOffsets::default());
let theme = Theme::std();
let colors: Vec<Rgba> = rendered
.commands
.iter()
.filter_map(|c| match c {
RenderCommand::FillRect { color, .. } => Some(color.clone()),
_ => None,
})
.collect();
let expect: Vec<Rgba> = ["thing.surface", "thing.scrim", "thing.control.fill"].iter().map(|n| theme.color(n).unwrap()).collect();
assert_eq!(colors, expect);
let scrim = fills(&rendered)[1];
assert_eq!(scrim, (0.0, 0.0, 800.0, 600.0));
}
#[test]
fn diagnostics_inside_an_overlay_reach_the_frame() {
let bad = Paint { background: Some(ColorRef::Token(ThemeToken { name: "nope".into() })), border: None, radius: 0.0 };
let invalid = BoxStyle { padding: edges(px(-3.0)), ..plain() };
let root = flat("root", plain(), vec![overlay("pop", Anchor::Viewport, false, vec![bx("inside", invalid, bad, vec![])])]);
let (laid, rendered) = inline(root, &pixels(1.0), &ScrollOffsets::default());
assert!(laid.diagnostics.iter().any(|d| d.code == Code::StyleValueInvalid && d.node.as_ref().map(|n| n.as_str()) == Some("inside")));
let codes: Vec<(Code, &str)> = rendered.diagnostics.iter().map(|d| (d.code, d.node.as_ref().unwrap().as_str())).collect();
assert_eq!(codes, [(Code::StyleValueInvalid, "inside"), (Code::ThemeTokenUnknown, "inside")]);
assert_eq!(rendered.diagnostics[1].detail, "nope");
}
#[test]
fn scale_divides_device_coordinates() {
let none = ScrollOffsets::default();
let tree = |scale: f32| {
let set = Fixture::F05ModalOverlay.load();
let mut state = MemState::from_fixture(Fixture::F05ModalOverlay);
state::script(Fixture::F05ModalOverlay, &mut state);
let bound = bind(&mut state, &set.surfaces[0]).unwrap();
draw(&bound, &pixels(scale), &none)
};
let (laid, rendered) = tree(1.5);
assert_eq!(rendered.placed.len(), laid.nodes.len());
for (node, placed) in laid.nodes.iter().zip(&rendered.placed) {
assert_eq!(node.id, placed.id);
assert_eq!(xywh(placed), (node.rect.x / 1.5, node.rect.y / 1.5, node.rect.w / 1.5, node.rect.h / 1.5), "{}", node.id.as_str());
}
// The dialog's fill is its border box in logical px.
let dialog = placed(&rendered, "dialog");
assert!(fills(&rendered).contains(&xywh(dialog)));
}
#[test]
fn an_unknown_token_is_the_visible_fallback_and_named_once() {
let root = flat("root", plain(), vec![
bx("b", sized(10.0, 10.0), filled("thing.nope"), vec![]),
Node::Text(TextNode { common: common("t"), content: lit_text("hi"), style_token: "nope-style".into(), wrap: false, max_lines: None, selectable: false }),
]);
let (_, rendered) = inline(root, &pixels(1.0), &ScrollOffsets::default());
let magenta = Rgba { r: 255, g: 0, b: 255, a: 255 };
assert!(rendered.commands.iter().any(|c| matches!(c, RenderCommand::FillRect { color, .. } if *color == magenta)));
assert!(rendered.commands.iter().any(|c| matches!(c, RenderCommand::Text { color, .. } if *color == magenta)));
let named: Vec<(&str, &str)> = rendered.diagnostics.iter().map(|d| (d.node.as_ref().unwrap().as_str(), d.detail.as_str())).collect();
assert_eq!(named, [("b", "thing.nope"), ("t", "nope-style")]);
assert!(rendered.diagnostics.iter().all(|d| d.code == Code::ThemeTokenUnknown));
}
#[test]
fn wrapping_text_is_one_command_per_engine_line_at_the_node_origin() {
let root = flat("root", BoxStyle { padding: edges(px(5.0)), direction: Direction::Column, ..plain() }, vec![Node::Text(TextNode {
common: common("t"),
content: lit_text("abcdefghij"),
style_token: "body".into(),
wrap: true,
max_lines: None,
selectable: false,
})]);
let width = BoxStyle { size: size2(px(34.0), Dimension::Auto), ..plain() };
let root = if let Node::Box(mut b) = root { b.style.size = width.size; Node::Box(b) } else { unreachable!() };
let (_, rendered) = inline(root.clone(), &pixels(1.0), &ScrollOffsets::default());
let t = xywh(placed(&rendered, "t"));
let lines: Vec<(f32, f32, String)> = rendered
.commands
.iter()
.filter_map(|c| match c {
RenderCommand::Text { origin, run: Run::Glyphs { glyphs, .. }, .. } => Some((origin.0, origin.1, glyphs.iter().map(|g| char::from_u32(g.id).unwrap()).collect())),
_ => None,
})
.collect();
assert_eq!(lines, [(t.0, t.1, "abc".into()), (t.0, t.1 + 16.0, "def".into()), (t.0, t.1 + 32.0, "ghi".into()), (t.0, t.1 + 48.0, "j".into())]);
assert_eq!(t.3, 64.0, "layout sized the leaf for the lines the engine returns");
// Cells: the line's characters, one row each.
let cells = frame(20.0, 10.0, 1.0, Metrics::Cells);
let root = if let Node::Box(mut b) = root { b.style.size = size2(px(5.0), Dimension::Auto); b.style.padding = edges(px(0.0)); Node::Box(b) } else { unreachable!() };
let (_, rendered) = inline(root, &cells, &ScrollOffsets::default());
let texts: Vec<(f32, f32, String)> = rendered
.commands
.iter()
.filter_map(|c| match c {
RenderCommand::Text { origin, run: Run::Cells { text, .. }, .. } => Some((origin.0, origin.1, text.clone())),
_ => None,
})
.collect();
assert_eq!(texts, [(0.0, 0.0, "abcde".into()), (0.0, 1.0, "fghij".into())]);
}
#[test]
fn leaves_draw_what_this_cut_owns() {
let error_text = Node::Text(TextNode { common: common("e"), content: TextSource::Bound(item_bind(path(&["Nope"]))), style_token: "body".into(), wrap: false, max_lines: None, selectable: false });
let use_node = Node::Use(UseNode {
common: common("u"),
composition: CompositionRef { publisher: "nobody".into(), name: seg("missing"), version: ver(1) },
args: vec![],
});
let root = flat("root", BoxStyle { direction: Direction::Column, ..plain() }, vec![error_text, use_node, embed("x", 20.0, 10.0)]);
let (laid, rendered) = inline(root, &pixels(1.0), &ScrollOffsets::default());
let theme = Theme::std();
let u = placed(&rendered, "u");
assert!(u.rect.w >= 16.0 && u.rect.h >= 16.0, "a Use placeholder is visible: {:?}", u.rect);
assert!(rendered.commands.iter().any(|c| matches!(c, RenderCommand::FillRect { color, .. } if *color == theme.color("thing.placeholder").unwrap())));
let strokes = rendered.commands.iter().filter(|c| matches!(c, RenderCommand::StrokeRect { color, .. } if *color == theme.color("thing.error").unwrap())).count();
assert!(strokes >= 1);
assert!(rendered.commands.iter().any(|c| matches!(c, RenderCommand::Embed { slot_id, .. } if slot_id == "x")));
assert_eq!(rendered.placed.len(), laid.nodes.len());
}
#[test]
fn an_oversize_asset_extent_through_bind_is_an_invalid_measure_and_renders() {
let provider = ProviderId::new("provider.render");
let catalog = AssetCatalog {
provider_id: provider.clone(),
catalog_id: seg("icons"),
version: ver(1),
assets: vec![AssetEntry { id: "huge".into(), media_type: "image/png".into(), uri: "asset://huge".into(), width: count(4_000_000), height: count(10) }],
};
let mut state = MemState::new();
state.put(&provider, &catalog);
let picture = Node::Image(ImageNode { common: common("pic"), catalog: "icons".into(), asset: "huge".into(), fit: ImageFit::Contain, alt: lit_text("alt") });
let tree = bind(&mut state, &surface_of(flat("root", BoxStyle { direction: Direction::Column, ..plain() }, vec![picture, embed("after", 10.0, 10.0)]))).unwrap();
let (laid, rendered) = draw(&tree, &pixels(1.0), &ScrollOffsets::default());
let invalid: Vec<&str> = laid.diagnostics.iter().filter(|d| d.code == Code::StyleValueInvalid).map(|d| d.detail.as_str()).collect();
assert_eq!(invalid, ["measure"]);
assert_eq!(rendered.diagnostics, laid.diagnostics);
assert!(balanced(&rendered.commands));
assert!(placed(&rendered, "after").rect.w == 10.0);
}
#[test]
fn random_documents_render_without_panic_balanced_and_equal() {
let mut seed = 0x9E37_79B9_7F4A_7C15u64;
let mut next = move || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed
};
let sizes = [0.0, 1.0, 7.5, 40.0, 100.0, 5000.0, 1e6, 1e7, -4.0, f64::NAN];
let overflows = [Overflow::Visible, Overflow::Clip, Overflow::Scroll];
let tokens = ["thing.surface", "thing.error", "unknown", "thing.scrim"];
for round in 0..300u64 {
let mut counter = 0u32;
let mut generated: Vec<String> = Vec::new();
fn grow(depth: u32, next: &mut dyn FnMut() -> u64, counter: &mut u32, generated: &mut Vec<String>, sizes: &[f64], overflows: &[Overflow], tokens: &[&str]) -> Node {
*counter += 1;
let id = format!("n{counter}");
generated.push(id.clone());
let pick = next();
match (pick % 7, depth) {
(0, _) => embed(&id, sizes[(next() % 10) as usize], sizes[(next() % 10) as usize]),
(1, _) => Node::Text(TextNode { common: common(&id), content: lit_text("some wrapping words"), style_token: tokens[(next() % 4) as usize].into(), wrap: next() % 2 == 0, max_lines: None, selectable: false }),
(2, d) if d < 3 => {
let anchor = if next() % 2 == 0 { Anchor::Viewport } else { at(&generated[(next() % generated.len() as u64) as usize]) };
let children = (0..(next() % 3)).map(|_| grow(depth + 1, next, counter, generated, sizes, overflows, tokens)).collect();
overlay(&id, anchor, next() % 2 == 0, children)
}
(_, d) if d < 4 => {
let mut style = BoxStyle { overflow: overflows[(next() % 3) as usize].clone(), ..plain() };
style.size = size2(px(sizes[(next() % 10) as usize]), px(sizes[(next() % 10) as usize]));
style.padding = edges(px(sizes[(next() % 10) as usize].min(40.0)));
style.direction = if next() % 2 == 0 { Direction::Row } else { Direction::Column };
let paint = Paint {
background: (next() % 2 == 0).then(|| ColorRef::Token(ThemeToken { name: tokens[(next() % 4) as usize].into() })),
border: (next() % 3 == 0).then(|| Border { color: ColorRef::Rgba(Rgba { r: 1, g: 2, b: 3, a: 4 }), width: sizes[(next() % 10) as usize] }),
radius: sizes[(next() % 10) as usize],
};
let children = (0..(next() % 4)).map(|_| grow(depth + 1, next, counter, generated, sizes, overflows, tokens)).collect();
bx(&id, style, paint, children)
}
_ => embed(&id, 3.0, 3.0),
}
}
let root = grow(0, &mut next, &mut counter, &mut generated, &sizes, &overflows, &tokens);
let ids = generated.clone();
let mut scroll = ScrollOffsets::default();
for id in &ids {
if next() % 3 != 0 {
continue;
}
scroll.set(nid(id), ((next() % 400) as f32 - 100.0, [f32::NAN, 1e30, 30.0, 400.0][(next() % 4) as usize]));
}
let frame = [pixels(1.0), pixels(1.5), pixels(2.0), frame(80.0, 30.0, 1.0, Metrics::Cells)][(round % 4) as usize];
let Ok(tree) = bind(&mut MemState::new(), &surface_of(root)) else { continue };
let Ok(laid) = layout(&tree, &frame, &mut measure(&frame)) else { continue };
let theme = Theme::std();
let first = render(&tree, &laid, &input(&frame, &scroll, &theme), &mut measure(&frame));
let second = render(&tree, &laid, &input(&frame, &scroll, &theme), &mut measure(&frame));
assert_eq!(first, second, "round {round}");
assert!(balanced(&first.commands), "round {round}");
assert_eq!(first.placed.len(), laid.nodes.len());
}
}
#[test]
fn a_clip_is_the_padding_box_and_its_radius_the_radius_less_the_border() {
let paint = Paint { background: None, border: Some(Border { color: ColorRef::Rgba(Rgba { r: 9, g: 8, b: 7, a: 6 }), width: 3.0 }), radius: 10.0 };
let root = flat("root", plain(), vec![bx("pane", BoxStyle { overflow: Overflow::Clip, ..sized(100.0, 50.0) }, paint.clone(), vec![embed("e", 5.0, 5.0)])]);
let (_, rendered) = inline(root.clone(), &pixels(2.0), &ScrollOffsets::default());
let pane = placed(&rendered, "pane").rect;
let stroke = RenderCommand::StrokeRect { rect: pane, radius: 10.0, width: 3.0, color: paint.border.as_ref().unwrap().color_literal() };
let clip = RenderCommand::ClipPush { rect: thing_core::layout::Rect { x: pane.x + 3.0, y: pane.y + 3.0, w: pane.w - 6.0, h: pane.h - 6.0 }, radius: 7.0 };
assert_eq!(&rendered.commands[..2], [stroke, clip]);
// A radius the border swallows leaves a square clip.
let mut square = paint;
square.radius = 2.0;
let (_, rendered) = inline(flat("root", plain(), vec![bx("pane", BoxStyle { overflow: Overflow::Clip, ..sized(100.0, 50.0) }, square, vec![])]), &pixels(1.0), &ScrollOffsets::default());
assert!(matches!(rendered.commands[1], RenderCommand::ClipPush { radius, .. } if radius == 0.0));
}
trait Literal {
fn color_literal(&self) -> Rgba;
}
impl Literal for Border {
fn color_literal(&self) -> Rgba {
match &self.color {
ColorRef::Rgba(rgba) => rgba.clone(),
ColorRef::Token(_) => unreachable!(),
}
}
}
#[test]
fn a_scrollbar_is_one_cell_thick_in_cells_and_the_theme_thickness_in_pixels() {
let pane = || flat("root", BoxStyle { overflow: Overflow::Scroll, ..sized(10.0, 5.0) }, vec![embed("e", 5.0, 20.0)]);
let (_, cells) = inline(pane(), &frame(20.0, 10.0, 1.0, Metrics::Cells), &ScrollOffsets::default());
assert_eq!(fills(&cells).iter().map(|f| f.2).collect::<Vec<_>>(), [1.0]);
let (_, device) = inline(pane(), &pixels(2.0), &ScrollOffsets::default());
assert_eq!(fills(&device).iter().map(|f| f.2).collect::<Vec<_>>(), [Theme::std().scrollbar]);
}

File diff suppressed because it is too large Load diff

View file

@ -1,12 +0,0 @@
[package]
name = "thing-state"
version = "0.1.0"
edition = "2024"
license = "MIT"
publish = false
[dependencies]
thing-core = { path = "../thing-core" }
cultcache-rs = { workspace = true }
rmp-serde = { workspace = true }
serde = { workspace = true }

View file

@ -1,184 +0,0 @@
//! The one by-name decode of a provider record. A state port implementation (`MemState` now,
//! thing-mesh next) calls `decode` with the record's payload and the catalog member rows of its
//! schema; core never sees bytes. The catalog names only a document's top-level members, so below
//! that level a payload decodes by its own shape.
//!
//! Registration contract: a provider's state record type must be registered with its entry type
//! equal to its schema id (`TYPE == SCHEMA_NAME`). A CultCache store names a record's schema by
//! its entry type, so the id a `Bind` names is the id the store holds only when the two are one
//! string; the member rows a reader finds are the rows published under that id.
use std::cell::RefCell;
use std::collections::HashSet;
use std::fmt;
use std::io::Cursor;
use cultcache_rs::{SchemaCatalogMember, check_payload_depth};
use thing_core::port::StateValue;
use serde::de::{self, DeserializeSeed, MapAccess, SeqAccess, Visitor};
/// Why a payload is not a `StateValue`. Display names slots, counts and positions, never a value.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum StateDecodeError {
/// The schema published no member rows: a reader cannot name what the writer did not publish.
NoMembers,
NotARecord,
TrailingBytes { count: usize },
TooDeep,
UndescribedSlot { slot: usize },
DuplicateKey { position: usize },
Extension,
Malformed,
}
impl fmt::Display for StateDecodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NoMembers => f.write_str("the schema published no member rows, so its members cannot be named"),
Self::NotARecord => f.write_str("the payload is not one MessagePack array"),
Self::TrailingBytes { count } => write!(f, "{count} bytes follow the record"),
Self::TooDeep => f.write_str("the payload nests deeper than CultCache admits"),
Self::UndescribedSlot { slot } => write!(f, "slot {slot} holds a value no member row names"),
Self::DuplicateKey { position } => write!(f, "the map repeats a key at entry {position}"),
Self::Extension => f.write_str("the payload holds a MessagePack extension value"),
Self::Malformed => f.write_str("the payload is not well-formed MessagePack"),
}
}
}
impl std::error::Error for StateDecodeError {}
/// Decode `payload`, one MessagePack array, into a `StateValue::Record` of the rows' member
/// names in slot order. A row whose slot lies past the array's end is `Nil`; a non-nil element at
/// a slot no row names is refused. An empty row list is refused.
pub fn decode(payload: &[u8], members: &[SchemaCatalogMember]) -> Result<StateValue, StateDecodeError> {
if members.is_empty() {
return Err(StateDecodeError::NoMembers);
}
check_payload_depth(payload).map_err(|_| StateDecodeError::TooDeep)?;
let failure = RefCell::new(None);
let mut reader = rmp_serde::Deserializer::new(Cursor::new(payload));
let value = match (Shape { failure: &failure }).deserialize(&mut reader) {
Ok(value) => value,
Err(_) => return Err(failure.into_inner().unwrap_or(StateDecodeError::Malformed)),
};
let StateValue::List(elements) = value else { return Err(StateDecodeError::NotARecord) };
let count = payload.len() - reader.position() as usize;
if count != 0 {
return Err(StateDecodeError::TrailingBytes { count });
}
let described: HashSet<usize> = members.iter().map(|row| row.slot as usize).collect();
if let Some(slot) =
elements.iter().enumerate().position(|(slot, value)| !described.contains(&slot) && *value != StateValue::Nil)
{
return Err(StateDecodeError::UndescribedSlot { slot });
}
let mut rows: Vec<&SchemaCatalogMember> = members.iter().collect();
rows.sort_by_key(|row| row.slot);
Ok(StateValue::Record(
rows.into_iter()
.map(|row| (row.member_name.clone(), elements.get(row.slot as usize).cloned().unwrap_or(StateValue::Nil)))
.collect(),
))
}
/// The shape of a payload below the catalog's reach. A semantic refusal is parked in `failure`
/// and surfaces as the serde error that unwinds the walk.
#[derive(Clone, Copy)]
struct Shape<'a> {
failure: &'a RefCell<Option<StateDecodeError>>,
}
impl Shape<'_> {
fn refuse<E: de::Error>(&self, error: StateDecodeError) -> E {
self.failure.borrow_mut().get_or_insert(error);
E::custom("refused")
}
}
impl<'de> DeserializeSeed<'de> for Shape<'_> {
type Value = StateValue;
fn deserialize<D: de::Deserializer<'de>>(self, deserializer: D) -> Result<StateValue, D::Error> {
deserializer.deserialize_any(self)
}
}
impl<'de> Visitor<'de> for Shape<'_> {
type Value = StateValue;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("a MessagePack value")
}
fn visit_unit<E: de::Error>(self) -> Result<StateValue, E> {
Ok(StateValue::Nil)
}
fn visit_none<E: de::Error>(self) -> Result<StateValue, E> {
Ok(StateValue::Nil)
}
fn visit_bool<E: de::Error>(self, value: bool) -> Result<StateValue, E> {
Ok(StateValue::Bool(value))
}
fn visit_i64<E: de::Error>(self, value: i64) -> Result<StateValue, E> {
Ok(StateValue::Int(value.into()))
}
fn visit_u64<E: de::Error>(self, value: u64) -> Result<StateValue, E> {
Ok(StateValue::Int(value.into()))
}
fn visit_f32<E: de::Error>(self, value: f32) -> Result<StateValue, E> {
Ok(StateValue::Float(value.into()))
}
fn visit_f64<E: de::Error>(self, value: f64) -> Result<StateValue, E> {
Ok(StateValue::Float(value))
}
fn visit_str<E: de::Error>(self, value: &str) -> Result<StateValue, E> {
Ok(StateValue::Text(value.into()))
}
fn visit_bytes<E: de::Error>(self, value: &[u8]) -> Result<StateValue, E> {
Ok(StateValue::Bytes(value.into()))
}
fn visit_newtype_struct<D: de::Deserializer<'de>>(self, _: D) -> Result<StateValue, D::Error> {
// rmp-serde presents an extension value as a newtype struct.
Err(self.refuse(StateDecodeError::Extension))
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<StateValue, A::Error> {
let mut elements = Vec::new();
while let Some(element) = seq.next_element_seed(self)? {
elements.push(element);
}
Ok(StateValue::List(elements))
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<StateValue, A::Error> {
let mut entries: Vec<(StateValue, StateValue)> = Vec::new();
while let Some(key) = map.next_key_seed(self)? {
let value = map.next_value_seed(self)?;
entries.push((key, value));
}
if entries.iter().all(|(key, _)| matches!(key, StateValue::Text(_))) {
let mut seen = HashSet::new();
let mut members = Vec::with_capacity(entries.len());
for (position, (key, value)) in entries.into_iter().enumerate() {
let StateValue::Text(name) = key else { unreachable!("every key is text") };
if !seen.insert(name.clone()) {
return Err(self.refuse(StateDecodeError::DuplicateKey { position }));
}
members.push((name, value));
}
Ok(StateValue::Record(members))
} else {
Ok(StateValue::List(entries.into_iter().map(|(key, value)| StateValue::List(vec![key, value])).collect()))
}
}
}

View file

@ -1,192 +0,0 @@
//! `thing_state::decode`: each StateValue arm, the slot rules, and the refusals. Payloads are
//! written byte by byte so the test does not lean on the encoder it checks.
use cultcache_rs::SchemaCatalogMember;
use thing_core::port::StateValue::{self, *};
use thing_state::{StateDecodeError, decode};
const CANARY: &str = "CANARY-7f3a91c2";
fn rows(names: &[&str]) -> Vec<SchemaCatalogMember> {
names
.iter()
.enumerate()
.map(|(slot, name)| SchemaCatalogMember {
slot: slot as u32,
member_name: (*name).into(),
type_name: "System.Object".into(),
is_reference: false,
is_many: false,
target_schema_name: None,
is_name: false,
index_alias: None,
})
.collect()
}
fn array(elements: &[Vec<u8>]) -> Vec<u8> {
assert!(elements.len() < 16);
let mut bytes = vec![0x90 | elements.len() as u8];
bytes.extend(elements.iter().flatten());
bytes
}
fn map(pairs: &[(Vec<u8>, Vec<u8>)]) -> Vec<u8> {
let mut bytes = vec![0x80 | pairs.len() as u8];
for (key, value) in pairs {
bytes.extend(key);
bytes.extend(value);
}
bytes
}
fn text(value: &str) -> Vec<u8> {
let mut bytes = vec![0xa0 | value.len() as u8];
bytes.extend(value.as_bytes());
bytes
}
fn int(value: u8) -> Vec<u8> {
assert!(value < 0x80);
vec![value]
}
fn nil() -> Vec<u8> {
vec![0xc0]
}
fn nested(levels: usize) -> Vec<u8> {
let mut bytes = vec![0x91; levels - 1];
bytes.push(0x90);
bytes
}
fn record(pairs: &[(&str, StateValue)]) -> StateValue {
Record(pairs.iter().map(|(name, value)| ((*name).to_string(), value.clone())).collect())
}
#[test]
fn every_arm_decodes_by_the_rows_names() {
let f64_bytes = [vec![0xcb], 2.5f64.to_be_bytes().to_vec()].concat();
let f32_bytes = [vec![0xca], 1.5f32.to_be_bytes().to_vec()].concat();
let u64_max = [vec![0xcf], vec![0xff; 8]].concat();
let i64_min = [vec![0xd3], i64::MIN.to_be_bytes().to_vec()].concat();
let payload = array(&[
nil(),
vec![0xc3],
u64_max,
i64_min,
f64_bytes,
f32_bytes,
text("hi"),
vec![0xc4, 2, 9, 8],
array(&[int(1), int(2)]),
map(&[(text("x"), int(1)), (text("y"), nil())]),
map(&[(int(1), text("one")), (text("k"), int(2))]),
]);
let names = ["Nil", "Bool", "Max", "Min", "F64", "F32", "Text", "Bytes", "List", "Rec", "PairList"];
let decoded = decode(&payload, &rows(&names)).unwrap();
assert_eq!(
decoded,
record(&[
("Nil", Nil),
("Bool", Bool(true)),
("Max", Int(u64::MAX as i128)),
("Min", Int(i64::MIN as i128)),
("F64", Float(2.5)),
("F32", Float(1.5)),
("Text", Text("hi".into())),
("Bytes", Bytes(vec![9, 8])),
("List", List(vec![Int(1), Int(2)])),
("Rec", record(&[("x", Int(1)), ("y", Nil)])),
("PairList", List(vec![List(vec![Int(1), Text("one".into())]), List(vec![Text("k".into()), Int(2)])])),
])
);
assert_eq!(decoded.member("Text"), Some(&Text("hi".into())));
assert_eq!(decoded.member("text"), None, "names match exactly, with no case folding");
}
#[test]
fn a_row_past_the_arrays_end_is_nil() {
let decoded = decode(&array(&[int(7)]), &rows(&["A", "B", "C"])).unwrap();
assert_eq!(decoded, record(&[("A", Int(7)), ("B", Nil), ("C", Nil)]));
}
#[test]
fn rows_decode_in_slot_order_whatever_the_order_given() {
let mut given = rows(&["A", "B"]);
given.reverse();
let decoded = decode(&array(&[int(1), int(2)]), &given).unwrap();
assert_eq!(decoded, record(&[("A", Int(1)), ("B", Int(2))]));
}
#[test]
fn a_non_nil_element_at_an_unnamed_slot_is_refused_and_a_nil_one_is_skipped() {
let mut described = rows(&["A", "B", "C"]);
described.remove(1); // slots 0 and 2
assert_eq!(
decode(&array(&[int(1), int(5), nil()]), &described),
Err(StateDecodeError::UndescribedSlot { slot: 1 })
);
assert_eq!(decode(&array(&[int(1), nil(), int(3)]), &described).unwrap(), record(&[("A", Int(1)), ("C", Int(3))]));
assert_eq!(decode(&array(&[int(1), int(2)]), &rows(&["A"])), Err(StateDecodeError::UndescribedSlot { slot: 1 }));
}
#[test]
fn no_member_rows_refuses_even_a_good_payload() {
assert_eq!(decode(&array(&[int(1)]), &[]), Err(StateDecodeError::NoMembers));
}
#[test]
fn the_payload_must_be_one_array_with_nothing_after_it() {
let names = rows(&["A"]);
assert_eq!(decode(&int(1), &names), Err(StateDecodeError::NotARecord));
assert_eq!(decode(&map(&[(text("A"), int(1))]), &names), Err(StateDecodeError::NotARecord));
let mut trailing = array(&[int(1)]);
trailing.extend([0xc0, 0xc0, 0xc0]);
assert_eq!(decode(&trailing, &names), Err(StateDecodeError::TrailingBytes { count: 3 }));
assert_eq!(decode(&[0x92, 0x01], &names), Err(StateDecodeError::Malformed));
assert_eq!(decode(&[], &names), Err(StateDecodeError::Malformed));
}
#[test]
fn an_extension_value_is_refused_wherever_it_sits() {
let names = rows(&["A"]);
assert_eq!(decode(&array(&[vec![0xd4, 0x01, 0x00]]), &names), Err(StateDecodeError::Extension));
assert_eq!(decode(&array(&[array(&[vec![0xd4, 0x01, 0x00]])]), &names), Err(StateDecodeError::Extension));
}
#[test]
fn a_repeated_text_key_is_refused_by_position() {
let names = rows(&["A"]);
let twice = map(&[(text("a"), int(1)), (text("b"), int(2)), (text("a"), int(3))]);
assert_eq!(decode(&array(&[twice]), &names), Err(StateDecodeError::DuplicateKey { position: 2 }));
// Distinct keys of different kinds are not duplicates.
let mixed = map(&[(int(1), int(1)), (text("1"), int(2))]);
assert!(decode(&array(&[mixed]), &names).is_ok());
}
#[test]
fn nesting_is_bounded_by_cultcaches_depth() {
let names = rows(&["A"]);
assert!(decode(&nested(256), &names).is_ok());
assert_eq!(decode(&nested(257), &names), Err(StateDecodeError::TooDeep));
}
#[test]
fn refusals_never_print_a_value() {
let names = rows(&["A"]);
let secret = text(CANARY);
let cases = [
array(&[secret.clone(), secret.clone()]),
[array(&[secret.clone()]), vec![0xc0]].concat(),
array(&[map(&[(text(CANARY), int(1)), (text(CANARY), int(2))])]),
array(&[secret.clone(), vec![0xd4, 0x01, 0x00]]),
secret.clone(),
];
for payload in cases {
let error = decode(&payload, &names).unwrap_err();
assert!(!error.to_string().contains(CANARY), "{error}");
assert!(!format!("{error:?}").contains(CANARY), "{error:?}");
}
}

View file

@ -1,16 +0,0 @@
[package]
name = "thing-testkit"
version = "0.1.0"
edition = "2024"
license = "MIT"
publish = false
[dependencies]
thing-contract = { path = "../thing-contract" }
cultcache-rs = { workspace = true }
thing-core = { path = "../thing-core" }
thing-state = { path = "../thing-state" }
anyhow = { workspace = true }
rmp-serde = { workspace = true }
serde = { workspace = true }

View file

@ -1,34 +0,0 @@
# thing-testkit fixtures
Each `.cc` is a CultCache single-file store of contract documents, written under the pinned
clock `2026-01-01T00:00:00Z`. The builders are `thing_testkit::fixture`; the bytes below are
frozen, and a normal test run only compares and reads them. The rows are the fixture table of
`docs/thing2-build-spec.md` section 2.5; map rules are those of the build spec.
| File | Holds | Map rules |
|---|---|---|
| `f01-swarm-dashboard.surface.cc` | One surface: a Grid Box root, a Text bound with a Number Format, a Repeat over a RecordsSource prefix whose template binds Item members, and a Button whose CommandRef is declared | 6, 9 |
| `f02-login-effect.surface.cc` | One surface (a Text TextInput and a Button whose command captures it, plus the declared resume command), the CommandInvocation of it, and its two results: Pending, then Completed with an `OpenExternal` effect whose `resume` names the declared command | 1, 2 |
| `f03-input-target.surface.cc` | One surface (an Image over a position: absolute Box with insets, holding a bound label) and the AssetCatalog the Image names | - |
| `f04-form.surface.cc` | One surface (Toggle, Slider, Select with literal options, TextInput of Number kind) and one command capturing all four, its invocation, and a Completed result declaring `clear_drafts` | 1 |
| `f05-modal-overlay.surface.cc` | One surface with a modal Overlay anchored to the viewport, a dismiss CommandRef and two Buttons inside | - |
| `f06-scroll-list.surface.cc` | One surface: a Box with `overflow: scroll` holding a Repeat over a RecordsSource prefix, template keyed by the item's `id` (the 1,000 items are provider state, not here) | - |
| `f07-plot.surface.cc` | One surface with a Plot of each mark (Line, Bar, Area) over a bound series, with and without axis bounds | - |
| `f08-embed-viewport.surface.cc` | One surface: an Embed of declared fixed size as a leaf between two Texts | - |
| `f09-composition-stack.surface.cc` | One surface: a `thing.std` stat Use, and a Use passing one argument of each ArgValue arm whose slot argument holds a second Use (two levels); plus the publisher CompositionDocument both name, whose body places the Slot node | 5 |
| `f10-hostile.surface.cc` | Four surfaces, one hostile shape each: an undeclared CommandRef, a duplicate id after expansion (the surface's `dup-use/shared-id` against the expansion of `dup-use`), an unresolved Use, and a Bind whose schema no fixture provides; plus the one composition (`dup`) the duplicate-id surface expands | 4, 5, 6 |
| `f11-deep.surface.cc` | One surface: the deepest Box chain whose payload CultCache's `check_payload_depth` accepts, found by the builder | - |
| `f11-deep-refused.bin` | The payload of the same chain one Box level deeper, raw: `check_payload_depth` refuses it at depth 257 and so does CultCache. No store can hold it | - |
| `f12-text-edge.surface.cc` | One surface of five Text nodes: bidi (Hebrew and Arabic in Latin), CJK wide characters, combining marks, emoji ZWJ sequences, and a paragraph long enough to wrap | - |
| `state-swarm.state.cc` | Provider state, not contract documents: f01's four swarm records (`summary`, `mind-1`..`mind-3`, schema `gamecult.thing.test.swarm.v1`) written with the test type registered, so the store's catalog publishes the member rows `Id`, `Name`, `Load` | - |
| `state-swarm-members-empty.state.cc` | The same four records written through a hand-implemented twin of the type, whose catalog publishes `[]`: every read of it is refused | - |
A payload the contract refuses cannot live in a store: f11's refused payload is a raw file here, and an
unknown union arm is `crates/thing-contract/tests/goldens/node-unknown-arm.bin`, read in place and fed to
`MemState::put_raw`.
## Regenerate
`THING_BLESS=1 cargo test -p thing-testkit --test fixtures every_fixture_round_trips` rewrites
the files (the two state stores: `--test state the_committed_stores`) through `golden::check`, the one bless door; review the diff before committing. Run
the tests without `THING_BLESS` to compare.

Some files were not shown because too many files have changed in this diff Show more