Compare commits

...
Sign in to create a new pull request.
Author SHA1 Message Date
8ca1bab380 Thing contract: an invocation names its source node and Repeat key chain (#22)
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Successful in 2m6s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Successful in 3m5s
2026-11-28 09:47:34 +00:00
63ed2e3b01 Thing 2.0: cells text (terminal widths and line breaking behind Measure) (#23)
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Has been cancelled
2026-11-28 09:01:01 +00:00
1033d30728 Thing 2.0: Core::frame and the closed InputEvent model (#21)
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Has been cancelled
2026-11-28 08:42:34 +00:00
c59a223e6c Thing contract: every runtime reads every other runtime's store (cut 1x) (#16)
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Successful in 5m21s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Has been cancelled
2026-11-28 08:34:05 +00:00
8fe8b1aaad Thing 2.0 cut 6b: render leaves (Image fit in core, Plot lowered to polylines and polygons) (#20)
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Successful in 2m46s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Successful in 6m0s
2026-11-28 07:41:33 +00:00
9da9080f8a Thing 2.0 cut 6a: render (the closed command list, overlays, scroll clipping) (#19)
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Has been cancelled
2026-11-28 07:00:01 +00:00
72d93006d0 Thing 2.0: images measure from their bound asset entry (#18)
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Has been cancelled
2026-11-28 06:33:58 +00:00
6f0cc63188 Thing 2.0 cut 5b: overlay roots and scroll extents (#17)
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Has been cancelled
2026-11-28 06:12:27 +00:00
2c08d99992 Thing 2.0 cut 5a: layout (Taffy, device pixels, a Measure seam for text) (#15)
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Has been cancelled
2026-11-28 05:33:03 +00:00
5a11b23c4e Thing 2.0: the Resolver (last good tree, version rule at intake, delete tombstones) (#14)
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Successful in 4m30s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Successful in 6m25s
2026-11-28 03:41:43 +00:00
d9b09ee5f4 Thing 2.0 cut 4: bind (the Binder binds resolved trees to provider state by name) (#13)
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Has been cancelled
2026-11-28 03:15:14 +00:00
491fc2020f Thing 2.0: state port values (StateValue, Record::State) and thing-state's by-name decode (#12)
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Successful in 3m30s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Successful in 3m37s
2026-11-28 02:05:00 +00:00
b1c007d8b1 Thing 2.0: CultLib pin to 4c9af401 (member rows), whole-value contract lists, resolve on any thread (#11)
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Has been cancelled
2026-11-28 01:26:23 +00:00
edeeee2129 Thing 2.0 cut 3: resolve (pure expansion, closed diagnostics, thing.std stat and card) (#10)
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Successful in 3m25s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Successful in 3m22s
2026-11-27 23:50:18 +00:00
e16a8eb917 Thing contract: Slot node, arm 13, in Rust, C# and TypeScript (thing2:ruling:composition-slot-node) (#9)
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Successful in 2m37s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Successful in 2m13s
2026-11-27 22:27:17 +00:00
4d254a1adf Thing 2.0: the remaining fixtures (testkit-fixtures) (#8)
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Successful in 2m43s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Successful in 1m43s
2026-11-27 20:52:51 +00:00
31f324f738 Thing contract, TypeScript: @gamecult/thing-contract (thing2 cut 1a) (#6)
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Has been cancelled
2026-11-27 20:43:02 +00:00
d052428094 Thing 2.0 cut 2: thing-core state port and thing-testkit (testkit-ports) (#7)
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Has been cancelled
2026-11-27 20:29:51 +00:00
7654e27364 Thing contract, C#: GameCult.Thing.Contract (thing2 cut 1b) (#5)
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Successful in 6m56s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Successful in 3m20s
2026-11-27 17:54:25 +00:00
159ad486e5 Merge pull request 'Thing 2.0 build spec (Meta t12-m0)' (#1) from libby/thing2-build-spec into main
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Successful in 3m29s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Successful in 2m57s
2026-11-11 00:20:06 +00:00
Libby
b6e06cf89a thing2 build spec: drop Brokkr gap, point site gap at Void, remove unsupported status claims
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (pull_request) Successful in 3m6s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (pull_request) Successful in 3m46s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 23:18:13 +00:00
Libby
366774dc4c thing2 build spec: mark union-parity follow-up resolved
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (pull_request) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 23:16:57 +00:00
Libby
9eb099be4d thing2 build spec: refresh against rulings in force
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (pull_request) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (pull_request) Has been cancelled
Cite code-home, port-cutover, compat-rebuild, freeze-fold, owns-text,
quarantine and frozen-surface rulings; note site and Brokkr port gaps;
close O11/O13 and the substrate-gap note; map pointer to r3 specs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-10 23:16:46 +00:00
Libby
3136ee8b80 Merge remote-tracking branch 'origin/main' into libby/thing2-build-spec
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (pull_request) Successful in 2m2s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (pull_request) Successful in 2m35s
2026-11-10 17:40:51 +00:00
fd7a48484d CI: concurrency group, no cancel on dispatch (#4)
All checks were successful
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Successful in 3m11s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Successful in 2m17s
2026-11-10 17:40:14 +00:00
4a6c04a073 CI: Windows leg workflow_dispatch only, PowerShell on Linux (#2)
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Successful in 3m12s
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Failing after 36s
2026-11-09 23:24:35 +00:00
Libby
ee8eec41f3 thing2 build spec: reconcile with rulings read from the eureka mind
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (pull_request) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (pull_request) Has been cancelled
Portable Eve contracts and browser lowering / windows-latest eve-browser-lowering (pull_request) Has been cancelled
Portable Eve contracts and browser lowering / windows-latest eve-contracts (pull_request) Has been cancelled
decode-stack-safety is Fixed (CultLib bbb98eaf); contract-ts/cs specs are r3;
discovery reads the eve advertisement through a port until its owner lands;
O11 tooling wording follows the thing-script-form question.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 10:35:43 +00:00
Libby
ebafda432f thing2 build spec: reconcile O11 with thing-script-form ruling
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (pull_request) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (pull_request) Has been cancelled
Portable Eve contracts and browser lowering / windows-latest eve-browser-lowering (pull_request) Has been cancelled
Portable Eve contracts and browser lowering / windows-latest eve-contracts (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 10:33:06 +00:00
Libby
e95f1ab5ba Thing 2.0 build spec: per-piece contracts, build order, tests, prior art
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (pull_request) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (pull_request) Has been cancelled
Portable Eve contracts and browser lowering / windows-latest eve-browser-lowering (pull_request) Has been cancelled
Portable Eve contracts and browser lowering / windows-latest eve-contracts (pull_request) Has been cancelled
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 07:41:49 +00:00
Libby
0ba536eec1 research: swarm dashboard sources and first cut
Some checks failed
Portable Eve contracts and browser lowering / ubuntu-latest eve-browser-lowering (push) Has been cancelled
Portable Eve contracts and browser lowering / ubuntu-latest eve-contracts (push) Has been cancelled
Portable Eve contracts and browser lowering / windows-latest eve-browser-lowering (push) Has been cancelled
Portable Eve contracts and browser lowering / windows-latest eve-contracts (push) Has been cancelled
Thing 2 contract state, Run/heartbeat/usage-readout sources, and the
smallest first cut for "is anyone working, and on what".

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-31 06:17:41 +00:00
Meta Vens
e119e76301 Merge readme-front-door: README front door
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 19:59:26 +02:00
198 changed files with 33714 additions and 144 deletions

View file

@ -8,6 +8,11 @@ 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 }}
@ -16,7 +21,10 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
matrix: matrix:
os: [windows-latest, ubuntu-latest] # No Windows runner exists: the windows-latest leg runs on workflow_dispatch only (GitHub or a
# 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:
@ -30,6 +38,14 @@ 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
@ -38,6 +54,23 @@ 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,12 +8,19 @@ 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/

233
Cargo.lock generated
View file

@ -17,12 +17,30 @@ 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"
@ -65,10 +83,29 @@ 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.2.0" version = "0.3.1"
source = "git+https://github.com/GameCult/CultLib.git?rev=b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7#b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7" source = "git+https://github.com/GameCult/CultLib.git?rev=4c9af401ae33812d862dde4ff3131433fc73c7dc#4c9af401ae33812d862dde4ff3131433fc73c7dc"
dependencies = [ dependencies = [
"anyhow", "anyhow",
"chrono", "chrono",
@ -79,20 +116,33 @@ dependencies = [
"serde", "serde",
"serde_bytes", "serde_bytes",
"serde_json", "serde_json",
"serde_stacker",
"sha2",
"stacker",
"uuid", "uuid",
"windows-sys", "windows-sys 0.59.0",
] ]
[[package]] [[package]]
name = "cultcache-rs-derive" name = "cultcache-rs-derive"
version = "0.1.0" version = "0.2.0"
source = "git+https://github.com/GameCult/CultLib.git?rev=b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7#b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7" source = "git+https://github.com/GameCult/CultLib.git?rev=4c9af401ae33812d862dde4ff3131433fc73c7dc#4c9af401ae33812d862dde4ff3131433fc73c7dc"
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"
@ -133,6 +183,16 @@ 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"
@ -212,6 +272,15 @@ 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"
@ -233,6 +302,16 @@ 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"
@ -276,6 +355,12 @@ 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"
@ -335,6 +420,28 @@ 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"
@ -347,6 +454,34 @@ 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"
@ -369,6 +504,18 @@ 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"
@ -378,14 +525,75 @@ 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",
"unicode-linebreak",
"unicode-segmentation",
"unicode-width",
]
[[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"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
[[package]]
name = "unicode-linebreak"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f"
[[package]]
name = "unicode-segmentation"
version = "1.13.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
[[package]]
name = "unicode-width"
version = "0.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557"
[[package]] [[package]]
name = "uuid" name = "uuid"
version = "1.28.0" version = "1.28.0"
@ -397,6 +605,12 @@ 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"
@ -532,6 +746,15 @@ 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,6 +4,12 @@ resolver = "2"
[workspace.dependencies] [workspace.dependencies]
anyhow = "1" anyhow = "1"
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7", package = "cultcache-rs" } cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "4c9af401ae33812d862dde4ff3131433fc73c7dc", 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"] }
# The terminal text tables, pinned exactly: a width is a golden. unicode-width drops its cjk
# tables, so ambiguous width is narrow.
unicode-width = { version = "=0.2.3", default-features = false }
unicode-segmentation = "=1.13.3"
unicode-linebreak = "=0.1.5"

View file

@ -12,4 +12,5 @@ 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)] #[cultcache(key = 3, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.AssetEntry>")]
pub assets: Vec<AssetEntry>, pub assets: Vec<AssetEntry>,
} }

View file

@ -37,6 +37,7 @@ 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,
@ -105,7 +106,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)] #[cultcache(key = 5, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.CapturedInput>")]
pub captured: Vec<CapturedInput>, pub captured: Vec<CapturedInput>,
#[cultcache(key = 6)] #[cultcache(key = 6)]
pub client: String, pub client: String,
@ -114,6 +115,14 @@ pub struct CommandInvocation {
pub issued_at: String, pub issued_at: String,
#[cultcache(key = 8)] #[cultcache(key = 8)]
pub delegation: Option<String>, pub delegation: Option<String>,
/// The activating node's declared id in the resolved tree. For a node inside a Repeat it is
/// the template's id, never an instance id. A confirmed invocation names the node confirmed;
/// a resumed one carries the source and items of the invocation whose result carried the effect.
#[cultcache(key = 9)]
pub source: NodeId,
/// The key of each Repeat instance enclosing the source, outermost first; empty outside any Repeat.
#[cultcache(key = 10, type_name = "System.Collections.Immutable.ImmutableArray<System.String>")]
pub items: Vec<String>,
} }
impl CommandInvocation { impl CommandInvocation {

View file

@ -9,6 +9,7 @@
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.
@ -72,6 +73,13 @@ 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);
@ -108,6 +116,13 @@ 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")) }
@ -166,6 +181,12 @@ 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,5 +1,6 @@
//! 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};
@ -20,6 +21,12 @@ macro_rules! id_type {
&self.0 &self.0
} }
} }
impl CultTypeName for $name {
fn cult_type_name() -> String {
"System.String".to_string()
}
}
}; };
} }
@ -65,6 +72,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(crate) fn asset_catalog_key(provider: &ProviderId, catalog_id: &Segment) -> String { pub 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,10 +9,11 @@
//! 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.
//! //!
//! Hazard: decoding these kinds from untrusted bytes on a default-size thread can abort the //! Stack hazard: `Node` nests without a bound of its own, and serde's `Deserialize` recurses
//! process inside CultCache's nesting bound before the bound refuses (the stack is not //! once per level, so a hostile payload nested deep enough overflows the stack of a caller that
//! bounded by nesting depth). The owner is `cultlib-gaps:follow_up:decode-stack-safety`; the //! decodes it directly. CultCache refuses such a payload on read and on write
//! tests decode on a 16 MiB thread until it lands. //! (`cultcache_rs::check_payload_depth`, 256 containers); a caller that decodes bytes outside a
//! CultCache must run that check first.
mod asset; mod asset;
mod command; mod command;
@ -26,12 +27,20 @@ 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}; pub use keys::{CommandId, NodeId, ProviderId, RecordKey, SchemaId, asset_catalog_key};
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,12 +1,14 @@
//! 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 for v1. //! composition document that names a reusable subtree. Arm keys are fixed: Slot (13) is the arm
//! added after the first twelve, and a decoder from before it refuses a record holding one
//! (CultCache's unknown-arm rule).
use cultcache_rs::{CultSlots, CultUnion, DatabaseEntry}; use 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, TextSource}; use crate::source::{Bind, BoolSource, CollectionSource, MemberPath, NumberSource, ParamName, TextSource};
use crate::style::{BoxStyle, Paint, Role}; use crate::style::{BoxStyle, Paint, Role};
/// What every node carries. /// What every node carries.
@ -21,6 +23,7 @@ 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),
@ -48,6 +51,8 @@ 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)]
@ -159,8 +164,10 @@ 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 kind: InputKind, pub input_kind: InputKind,
#[cultcache(key = 3)] #[cultcache(key = 3)]
pub placeholder: TextSource, pub placeholder: TextSource,
#[cultcache(key = 4)] #[cultcache(key = 4)]
@ -309,6 +316,13 @@ 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)]
@ -319,6 +333,15 @@ 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)]
@ -422,7 +445,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)] #[cultcache(key = 5, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.CommandDecl>")]
pub commands: Vec<CommandDecl>, pub commands: Vec<CommandDecl>,
} }
@ -442,7 +465,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)] #[cultcache(key = 3, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.ParamDecl>")]
pub params: Vec<ParamDecl>, pub params: Vec<ParamDecl>,
#[cultcache(key = 4)] #[cultcache(key = 4)]
pub body: Node, pub body: Node,

View file

@ -41,6 +41,7 @@ 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,7 +81,9 @@ pub enum StateSource {
Item, Item,
} }
/// A state record. An absent provider is the publisher of the document. /// A state record. An absent provider is the publisher of the document. `schema` is the id the
/// provider's record type is registered under in its store: a provider's state type must have its
/// entry type equal to that schema id, because a store names a record's schema by its entry type.
#[derive(Clone, Debug, PartialEq, CultSlots)] #[derive(Clone, Debug, PartialEq, CultSlots)]
pub struct StateRef { pub struct StateRef {
#[cultcache(key = 0)] #[cultcache(key = 0)]

View file

@ -0,0 +1,63 @@
//! The catalog rows the five document kinds publish are the rows the C# package declares:
//! `tests/thing-contract-parity/catalog-members.tsv`, which NameSetTests (C#) and parity.test.ts
//! (TypeScript) are held to as well. Schema ids differ by writer, so the comparison is by group,
//! as `catalogGroups` in parity.test.ts makes it.
use std::path::PathBuf;
use cultcache_rs::{DatabaseEntry, SchemaCatalogMember, SingleFileMessagePackBackingStore};
use thing_contract::*;
fn tsv_groups() -> Vec<String> {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/thing-contract-parity/catalog-members.tsv");
let text = std::fs::read_to_string(path).unwrap();
let mut groups: Vec<(String, Vec<String>)> = Vec::new();
for row in text.lines().filter(|line| !line.trim().is_empty()) {
let (schema, rest) = row.split_once('\t').unwrap();
match groups.iter_mut().find(|(id, _)| id == schema) {
Some((_, rows)) => rows.push(rest.to_string()),
None => groups.push((schema.to_string(), vec![rest.to_string()])),
}
}
sorted(groups.into_iter().map(|(_, rows)| rows.join("\n")).collect())
}
fn group(members: &[SchemaCatalogMember]) -> String {
members.iter().map(|m| format!("{}\t{}\t{}", m.slot, m.member_name, m.type_name)).collect::<Vec<_>>().join("\n")
}
fn sorted(mut groups: Vec<String>) -> Vec<String> {
groups.sort();
groups
}
#[test]
fn rows_equal_the_csharp_file() {
let mine = sorted(vec![
group(&SurfaceDocument::schema_members()),
group(&CompositionDocument::schema_members()),
group(&CommandInvocation::schema_members()),
group(&CommandResult::schema_members()),
group(&AssetCatalog::schema_members()),
]);
assert_eq!(mine, tsv_groups());
}
#[test]
fn every_committed_store_carries_the_rows() {
// Each runtime's committed store, this crate's own included, declares the C# catalog. The Rust
// reader does not compare member type names when it opens a store, so a drifted name in a
// store another runtime wrote fails here. A store is copied first: reading it creates a lock
// file beside it.
for file in ["written-by-rs.cc", "written-by-cs.cc", "written-by-ts.cc"] {
let committed = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/thing-contract-parity").join(file);
let work = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!("catalog-members-{file}"));
std::fs::create_dir_all(&work).unwrap();
let copy = work.join(file);
std::fs::copy(committed, &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(), "{file}");
let _ = std::fs::remove_dir_all(&work);
}
}

View file

@ -0,0 +1,63 @@
//! The stores the other two runtimes wrote. `written-by-cs.cc` and `written-by-ts.cc` in
//! `tests/thing-contract-parity` are read here, never written: each opens to exactly the five
//! records, each re-encodes to its value golden, and each sits under the key the other runtimes
//! key it by. The file is copied first: reading a store creates a lock file beside it.
use std::fmt::Debug;
use std::path::PathBuf;
use cultcache_rs::DatabaseEntry;
use thing_contract::*;
use thing_testkit::{golden, store};
fn parity_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/thing-contract-parity")
}
fn goldens_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
}
fn scratch(purpose: &str, bytes: &[u8]) -> PathBuf {
static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let work = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!("foreign-{purpose}-{serial}"));
std::fs::create_dir_all(&work).unwrap();
let copy = work.join("store.cc");
std::fs::write(&copy, bytes).unwrap();
copy
}
fn assert_record<T: DatabaseEntry + Debug>(cache: &cultcache_rs::CultCache, key: &str, golden_name: &str) {
let records = cache.get_all_with_keys::<T>().unwrap();
assert_eq!(records.len(), 1, "{golden_name}: one record of the kind");
let (found, value) = &records[0];
assert_eq!(found, key, "{golden_name}: keyed as the other runtimes key it");
let expected = golden::read(&goldens_dir(), &format!("{golden_name}.bin"));
assert_eq!(rmp_serde::to_vec(value).unwrap(), expected, "{golden_name}: re-encodes to its golden");
}
fn assert_five_records(cache: &cultcache_rs::CultCache) {
assert_record::<SurfaceDocument>(cache, "thing:surface:provider.a.main", "surface-all-arms");
assert_record::<CompositionDocument>(cache, "thing:composition:provider.a.panel.v3", "composition-all-params");
assert_record::<CommandInvocation>(cache, "thing:invocation:3f2b8c1e-5d44-4a6b-9a07-1c2d3e4f5a6b", "invocation-all-inputs");
assert_record::<CommandResult>(cache, "thing:result:3f2b8c1e-5d44-4a6b-9a07-1c2d3e4f5a6b.1", "result-pending");
assert_record::<AssetCatalog>(cache, "thing:asset_catalog:provider.a.icons", "asset-catalog");
assert_eq!(cache.snapshot().len(), 5, "no record beyond the five");
}
fn open_foreign(file: &str) {
let copy = scratch("foreign", &std::fs::read(parity_dir().join(file)).unwrap());
assert_five_records(&store::open(&copy));
let _ = std::fs::remove_dir_all(copy.parent().unwrap());
}
#[test]
fn the_store_csharp_wrote_opens_to_five_records_that_re_encode_to_the_goldens() {
open_foreign("written-by-cs.cc");
}
#[test]
fn the_store_typescript_wrote_opens_to_five_records_that_re_encode_to_the_goldens() {
open_foreign("written-by-ts.cc");
}

View file

@ -2,42 +2,29 @@
//! 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 common::*; use thing_testkit::{build::*, golden, store};
use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry, SingleFileMessagePackBackingStore}; use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry};
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")
} }
fn blessing() -> bool { /// Where the stores of all three runtimes live; this crate writes `written-by-rs.cc` there.
std::env::var("THING_BLESS").as_deref() == Ok("1") fn parity_dir() -> PathBuf {
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/thing-contract-parity")
} }
/// Bless the file or compare against it. Returns the committed bytes. // A value that must never appear in a refusal.
fn golden_bytes(file: &str, produced: &[u8]) -> Vec<u8> { const CANARY: &str = "CANARY-7f3a91c2";
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_bytes(&format!("{name}.bin"), &produced); let committed = golden::check(&goldens_dir(), &format!("{name}.bin"), &produced);
let decoded: T = rmp_serde::from_slice(&committed).unwrap_or_else(|error| panic!("{name}: {error}")); 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");
@ -150,7 +137,7 @@ fn full_surface() -> SurfaceDocument {
Node::TextInput(TextInputNode { Node::TextInput(TextInputNode {
common: common("name-input"), common: common("name-input"),
multiline: true, multiline: true,
kind: InputKind::Number, input_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"),
@ -158,7 +145,7 @@ fn full_surface() -> SurfaceDocument {
Node::TextInput(TextInputNode { Node::TextInput(TextInputNode {
common: common("title-input"), common: common("title-input"),
multiline: false, multiline: false,
kind: InputKind::Text, input_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"),
@ -384,7 +371,10 @@ 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("panel-root", vec![text("panel-title", "t"), inner_use]), body: boxed(
"panel-root",
vec![text("panel-title", "t"), inner_use, Node::Slot(SlotNode { param: param("body") })],
),
} }
} }
@ -435,26 +425,17 @@ 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 _ = std::fs::remove_file(path); let mut cache = store::create(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();
put(&mut cache, &surface.record_key(), &surface); store::put_pinned(&mut cache, &surface.record_key(), &surface);
put(&mut cache, &composition.record_key(), &composition); store::put_pinned(&mut cache, &composition.record_key(), &composition);
put(&mut cache, &invocation.record_key(), &invocation); store::put_pinned(&mut cache, &invocation.record_key(), &invocation);
put(&mut cache, &result.record_key(), &result); store::put_pinned(&mut cache, &result.record_key(), &result);
put(&mut cache, &catalog.record_key(), &catalog); store::put_pinned(&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 {
@ -462,17 +443,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: PINNED_CLOCK.into(), stored_at: store::PINNED_CLOCK.into(),
schema_id: Some(T::TYPE.into()), schema_id: Some(T::TYPE.into()),
} }
} }
fn open_store(path: &std::path::Path) -> CultCache { #[test]
let mut cache = CultCache::new(); fn slot_arm_bytes() {
ThingContract.register_entries(&mut cache).unwrap(); let slot = Node::Slot(SlotNode { param: param("body") });
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap(); let bytes = rmp_serde::to_vec(&slot).unwrap();
cache.pull_all_backing_stores().unwrap(); assert_eq!(bytes, [0x92, 0x0D, 0x91, 0x91, 0xA4, 0x62, 0x6F, 0x64, 0x79]);
cache assert_eq!(rmp_serde::from_slice::<Node>(&bytes).unwrap(), slot);
} }
#[test] #[test]
@ -491,7 +472,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_bytes(&format!("{name}.bin"), bytes); golden::check(&goldens_dir(), &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())
@ -504,10 +485,11 @@ 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_bytes("surface.cc", &std::fs::read(&scratch).unwrap()); let parity = parity_dir();
let reopened = goldens_dir().join("surface.cc"); let committed = golden::check(&parity, "written-by-rs.cc", &std::fs::read(&scratch).unwrap());
let reopened = parity.join("written-by-rs.cc");
assert_eq!(std::fs::read(&reopened).unwrap(), committed); assert_eq!(std::fs::read(&reopened).unwrap(), committed);
let cache = open_store(&scratch); let cache = store::open(&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();
@ -553,10 +535,11 @@ 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. // A surface whose root is an arm key the Node union does not declare: 14 is the first key
// Node does not declare (Slot is 13).
( (
"node-unknown-arm", "node-unknown-arm",
rmp_serde::to_vec(&("provider.a", "main", 1i64, CANARY, (13i32, (CANARY,)), unit)).unwrap(), rmp_serde::to_vec(&("provider.a", "main", 1i64, CANARY, (14i32, (CANARY,)), unit)).unwrap(),
), ),
// A result whose outcome is an arm key the Outcome union does not declare. // 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()),
@ -591,7 +574,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_bytes(&format!("{name}.bin"), &payloads[name]); let committed = |name: &str| golden::check(&goldens_dir(), &format!("{name}.bin"), &payloads[name]);
// Stored under their key, each is refused naming the kind and the key, never a value. // 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] = [
@ -623,7 +606,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", "13"), ("outcome-unknown-arm", "Outcome", "4")] { for (name, union, key) in [("node-unknown-arm", "Node", "14"), ("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()
@ -665,13 +648,6 @@ 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() {
@ -698,15 +674,12 @@ fn deep_tree_body() {
}; };
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 = CultCache::new(); let mut cache = store::create(&path);
ThingContract.register_entries(&mut cache).unwrap(); store::put_pinned(&mut cache, &deep.record_key(), &deep);
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap(); store::put_pinned(&mut cache, &wide.record_key(), &wide);
put(&mut cache, &deep.record_key(), &deep);
put(&mut cache, &wide.record_key(), &wide);
} }
let cache = open_store(&path); let cache = store::open(&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,9 +12,9 @@ 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 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 | | `surface-all-arms.bin` | `gamecult.thing.surface.v1` | One surface with 13 of the 14 node arms (Box 0, Text 1, Image 2, Button 3, Toggle 4, Slider 5, TextInput 6 as both input kinds, Text 0 and Number 1, Select 7, Repeat 8, Overlay 9, Plot 10, Embed 11, Use 12; Slot 13 is in `composition-all-params`, a body being where a slot stands), a Box chain four levels deep, every text, number and bool source arm, every Format arm, both state sources, both member steps, every dimension and colour arm, and two declared commands |
| `composition-all-params.bin` | `gamecult.thing.composition.v1` | A composition with one parameter of each of the 7 kinds, whose body uses a composition with one argument of each of the 7 argument arms | | `composition-all-params.bin` | `gamecult.thing.composition.v1` | A composition with one parameter of each of the 7 kinds, whose body uses a composition with one argument of each of the 7 argument arms and places the body slot (Slot 13) last in its root's children |
| `invocation-all-inputs.bin` | `gamecult.thing.command_invocation.v1` | An invocation with a payload record of bin bytes and one captured input of each of the 4 input arms | | `invocation-all-inputs.bin` | `gamecult.thing.command_invocation.v1` | An invocation with a payload record of bin bytes and one captured input of each of the 4 input arms, source `go-button` and items `[outer, inner]` |
| `result-pending.bin` | `gamecult.thing.command_result.v1` | Outcome Pending, seq 1 | | `result-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 |
| `result-completed-open-surface.bin` | same | Completed with no source version and the OpenSurface effect | | `result-completed-open-surface.bin` | same | Completed with no source version and the OpenSurface effect |
@ -23,14 +23,13 @@ when absent. Arm keys are fixed for v1.
| `result-denied-no-node.bin` | same | Denied with a nil node | | `result-denied-no-node.bin` | same | Denied with a nil node |
| `result-failed.bin` | same | Failed | | `result-failed.bin` | same | Failed |
| `asset-catalog.bin` | `gamecult.thing.asset_catalog.v1` | Two assets | | `asset-catalog.bin` | `gamecult.thing.asset_catalog.v1` | Two assets |
| `surface.cc` | single-file store | One record of each of the five kinds, written under the pinned clock `2026-01-01T00:00:00Z`; reading it and writing it again gives the same bytes |
## Refusals and tolerance ## Refusals and tolerance
| 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 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 | | `node-unknown-arm.bin` | a surface whose root node has arm key 14, which Node does not declare | refused; the error names the kind and the record key, and decoded directly it names the union Node and the key 14, and never a value |
| `outcome-unknown-arm.bin` | a result whose outcome has arm key 4, which Outcome does not declare | refused in the same way, naming the union Outcome and the key 4 | | `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,3 +39,9 @@ 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 (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

@ -0,0 +1,132 @@
//! 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,6 +1,4 @@
mod common; use thing_testkit::build::*;
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

@ -0,0 +1,20 @@
[package]
name = "thing-core"
version = "0.1.0"
edition = "2024"
license = "MIT"
publish = false
# Normal dependencies are thing-contract, stacker, taffy and the three Unicode tables of the Cells
# text engine (unicode-width, unicode-segmentation, unicode-linebreak): layout and terminal text
# are thing-core's job, and no Taffy type is in its public API.
[dependencies]
thing-contract = { path = "../thing-contract" }
stacker = "0.1.25"
taffy.workspace = true
unicode-width.workspace = true
unicode-segmentation.workspace = true
unicode-linebreak.workspace = true
[dev-dependencies]
thing-testkit = { path = "../thing-testkit" }

View file

@ -0,0 +1,172 @@
//! 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

@ -0,0 +1,346 @@
//! 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

@ -0,0 +1,199 @@
//! 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

@ -0,0 +1,402 @@
//! 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

@ -0,0 +1,65 @@
//! 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

@ -0,0 +1,171 @@
//! The frame entry: one `Core::frame` call per frame the host makes drains the port, resolves,
//! binds, lays out and renders. Core owns the pipeline order and is the only caller of
//! `StatePort::drain`; it reads no clock, sleeps nowhere and never awaits. Later cuts extend
//! `frame` in place with their own step; there is no second entry.
use thing_contract::{DatabaseEntry, ProviderId, RecordKey, SchemaId, SurfaceDocument};
use crate::bind::Binder;
use crate::diagnostic::Diagnostic;
use crate::input::InputEvent;
use crate::layout::{LaidTree, LayoutError, LayoutFrame, Measure, Metrics, layout};
use crate::port::{Address, Change, Interest, Ledger, Lookup, StatePort};
use crate::render::{RenderCommand, RenderInput, Rendered, ScrollOffsets, render};
use crate::resolve::{Limits, Resolver};
use crate::theme::Theme;
use crate::time::Timestamp;
/// What a core is built with. `metrics` is the mode of the one `Measure` core owns.
#[derive(Clone, Debug, PartialEq)]
pub struct Config {
pub limits: Limits,
pub metrics: Metrics,
}
impl Config {
pub fn new(metrics: Metrics) -> Self {
Self { limits: Limits::default(), metrics }
}
}
/// The ports lent to one frame. The host owns its state port and changes it between frames;
/// it lends the same port every frame, because core's `Ledger` counts the subscriptions it made
/// on that port.
pub struct Ports<'a> {
pub state: &'a mut dyn StatePort,
}
/// What the host tells core each frame. `viewport` is the one writer of size: logical px
/// (`Metrics::Pixels`) or cells (`Metrics::Cells`), the space `LayoutFrame` takes; a resize is
/// the next frame's viewport.
#[derive(Clone, Debug, PartialEq)]
pub struct FrameInput {
pub now: Timestamp,
pub viewport: (f32, f32),
pub scale: f32,
pub events: Vec<InputEvent>,
}
/// What a frame hands back. Later cuts add fields; hosts keep compiling.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct FrameOutput {
pub commands: Vec<RenderCommand>,
pub diagnostics: Vec<Diagnostic>,
/// When the host should call `frame` again with nothing else to say; `None` while nothing in
/// core depends on time.
pub next_wake: Option<Timestamp>,
}
pub struct Core {
metrics: Metrics,
measure: Box<dyn Measure>,
resolver: Resolver,
binder: Binder,
ledger: Ledger,
scroll: ScrollOffsets,
theme: Theme,
/// The surface `show` named, and the one whose interest and trees are held.
wanted: Option<Address>,
shown: Option<Address>,
/// The last good frame: what the user saw, which hit-test reads.
last: Option<(LaidTree, Rendered)>,
}
impl Core {
pub fn new(config: Config, measure: Box<dyn Measure>) -> Self {
Self {
metrics: config.metrics,
measure,
resolver: Resolver::new(config.limits.clone()),
binder: Binder::new(config.limits),
ledger: Ledger::new(),
scroll: ScrollOffsets::default(),
theme: Theme::std(),
wanted: None,
shown: None,
last: None,
}
}
/// Name the one surface displayed. It takes effect at the next frame.
pub fn show(&mut self, provider: ProviderId, key: RecordKey) {
self.wanted = Some(Address { provider, schema: SchemaId::new(SurfaceDocument::SCHEMA_NAME), key });
}
pub fn frame(&mut self, input: FrameInput, ports: Ports<'_>) -> FrameOutput {
// Input routes only to owners that exist; none does yet, so events change nothing.
let FrameInput { now: _, viewport, scale, events: _ } = input;
let port = ports.state;
let mut changes = Vec::new();
if self.wanted != self.shown {
self.switch(port, &mut changes);
}
changes.extend(port.drain());
let mut diagnostics = Vec::new();
for change in &changes {
let intake = self.resolver.apply(change, port, &mut self.ledger);
diagnostics.extend(intake.diagnostics);
for (key, replaced) in intake.changed {
if replaced {
if let Some(tree) = self.resolver.tree(&key).cloned() {
diagnostics.extend(self.binder.bind(tree, port, &mut self.ledger).diagnostics);
}
} else {
self.binder.forget(&key, port, &mut self.ledger);
}
}
diagnostics.extend(self.binder.apply(change, port, &mut self.ledger).diagnostics);
}
let commands = self.draw(viewport, scale, &mut diagnostics);
FrameOutput { commands, diagnostics, next_wake: None }
}
/// Leave the surface shown and take the one wanted: the interest is held before the one read,
/// and what the read finds enters as a change like any republish.
fn switch(&mut self, port: &mut dyn StatePort, changes: &mut Vec<Change>) {
if let Some(old) = self.shown.take() {
self.resolver.forget(old.key.as_str(), port, &mut self.ledger);
self.binder.forget(old.key.as_str(), port, &mut self.ledger);
self.ledger.release(port, &Interest::Record(old));
self.scroll = ScrollOffsets::default();
self.last = None;
}
if let Some(new) = self.wanted.clone() {
self.ledger.hold(port, &Interest::Record(new.clone()));
match port.read(&new) {
Lookup::Present(entry) => changes.push(Change::Upsert(entry)),
Lookup::Refused(refusal) => changes.push(Change::Refused(refusal)),
Lookup::Absent => {}
}
}
self.shown = self.wanted.clone();
}
fn draw(&mut self, viewport: (f32, f32), scale: f32, diagnostics: &mut Vec<Diagnostic>) -> Vec<RenderCommand> {
let tree = self.shown.as_ref().and_then(|address| self.binder.tree(address.key.as_str()));
let Some(tree) = tree else {
self.last = None;
return Vec::new();
};
let frame = LayoutFrame { viewport, scale, metrics: self.metrics };
match layout(tree, &frame, self.measure.as_mut()) {
Ok(laid) => {
let input = RenderInput { scale, metrics: self.metrics, viewport, scroll: &self.scroll, theme: &self.theme };
let rendered = render(tree, &laid, &input, self.measure.as_mut());
diagnostics.extend(rendered.diagnostics.iter().cloned());
let commands = rendered.commands.clone();
self.last = Some((laid, rendered));
commands
}
Err(LayoutError::OutOfRange(diagnostic)) => {
diagnostics.push(diagnostic);
self.last.as_ref().map(|(_, rendered)| rendered.commands.clone()).unwrap_or_default()
}
// The host's room, not a document fault: nothing is drawn and the last good frame stays.
Err(LayoutError::Frame(_)) => Vec::new(),
}
}
}

View file

@ -0,0 +1,83 @@
//! The closed input model every host speaks to core. It is not `#[non_exhaustive]`: a new
//! variant is a contract revision every host compiles against.
//!
//! The viewport and the scale are not events: they are `FrameInput` fields, and a resize is the
//! next frame's viewport. Time is not an event either (`FrameInput::now`).
/// One thing the user did, in the order the host saw it.
#[derive(Clone, Debug, PartialEq)]
pub enum InputEvent {
/// A key press or auto-repeat (`repeat: true`). A release never enters: a terminal
/// reports Release on Windows and the TUI drops it, and the web host drops keyup. `Char` is the
/// character the keyboard layout produced (Shift+a is `Char('A')` with `shift` set;
/// Shift+Tab is `Tab` with `shift`). A typing key emits `Key` then `Text`, in that order (DOM
/// keydown precedes beforeinput; a window system's key event carries text beside the key; egui emits
/// Event::Key then Event::Text); a Ctrl or Alt chord emits `Key` only. Commands bind to `Key`.
Key { key: Key, modifiers: Modifiers, repeat: bool },
/// Committed text to insert; a paste is `Text`. Text inserts only from `Text`, so nothing
/// inserts twice.
Text(String),
/// The IME preedit, replacing any earlier one; empty `text` ends it without commit, and the
/// commit arrives as `Text` (DOM compositionupdate/compositionend; a window system's IME preedit and commit).
/// `cursor` is UTF-8 byte offsets into `text`, the window-system convention; the web host converts the
/// DOM's UTF-16 offsets.
Compose { text: String, cursor: Option<(u32, u32)> },
/// `at` is in the space `Placed` is in: logical px, or cells where a terminal cell
/// `(col, row)` is its centre `(col + 0.5, row + 0.5)`, the point the TUI's paint covers a
/// cell by, so a hit and a drawn cell agree.
PointerDown { at: (f32, f32), button: PointerButton, modifiers: Modifiers },
/// Sent with or without a button held.
PointerMove { at: (f32, f32), modifiers: Modifiers },
PointerUp { at: (f32, f32), button: PointerButton, modifiers: Modifiers },
/// The platform took the pointer (DOM pointercancel; the web host uses setPointerCapture so
/// an up outside the canvas still arrives): a pending press is dropped and no up follows.
PointerCancel,
/// `delta` positive y moves content toward its end (the scroll offset grows), positive x
/// right: the DOM WheelEvent sign. A terminal's ScrollDown is `(0, 1)` `Lines`; a
/// window system whose line delta has the opposite sign is negated by its host. `Units` are logical px or
/// cells; `Lines` are converted by core.
Wheel { at: (f32, f32), delta: (f32, f32), unit: WheelUnit, modifiers: Modifiers },
/// The host window or terminal gained (`true`) or lost focus.
Focus(bool),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Key {
Char(char),
Enter,
Tab,
Backspace,
Delete,
Escape,
Left,
Right,
Up,
Down,
Home,
End,
PageUp,
PageDown,
Insert,
F(u8),
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Modifiers {
pub shift: bool,
pub ctrl: bool,
pub alt: bool,
pub meta: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PointerButton {
Primary,
Secondary,
Middle,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum WheelUnit {
Units,
Lines,
}

View file

@ -0,0 +1,5 @@
//! What a host tells core about its user: the closed `InputEvent` vocabulary.
pub mod event;
pub use event::{InputEvent, Key, Modifiers, PointerButton, WheelUnit};

View file

@ -0,0 +1,189 @@
//! The Measure seam: what a leaf's intrinsic size is. Text, controls and images are sized by a
//! `Measure` the frame owner composes (cut 9a ships Pixels and Cells); layout never estimates
//! them. Taffy's own types stop at this file: `Leaf` and `Constraint` are plain data.
use taffy::{AvailableSpace, Size};
use thing_contract::NodeId;
use crate::bind::Bound;
use crate::text::CellText;
/// The room a leaf is offered on one axis.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Avail {
Definite(f32),
MinContent,
MaxContent,
}
/// What a leaf is asked, in logical px (Pixels) or cells (Cells). `known` is a size the parent
/// already fixed on an axis; `available` is the room on each axis, `[width, height]`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Constraint {
pub known: [Option<f32>; 2],
pub available: [Avail; 2],
}
/// A leaf node with the values it shows, borrowed from the bound tree.
#[derive(Clone, Copy, Debug)]
pub enum Leaf<'a> {
Text { node: &'a NodeId, content: &'a Bound, style_token: &'a str, wrap: bool, max_lines: Option<u32> },
TextInput { node: &'a NodeId, multiline: bool, placeholder: &'a Bound, value: &'a Bound },
Toggle { node: &'a NodeId },
Slider { node: &'a NodeId },
Select { node: &'a NodeId, selected: &'a Bound },
Image { node: &'a NodeId, asset: &'a Bound },
}
/// A face the text engine drew with. Opaque to core: the backend maps it to its own font.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FontId(pub u32);
/// One placed glyph of a line: the engine's glyph id and its position in the line, logical px.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Glyph {
pub id: u32,
pub x: f32,
pub y: f32,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct CellStyle {
pub bold: bool,
pub italic: bool,
pub underline: bool,
}
/// What one line of text is made of: shaped glyphs (Pixels) or characters (Cells).
#[derive(Clone, Debug, PartialEq)]
pub enum Run {
Glyphs { font: FontId, size: f32, glyphs: Vec<Glyph> },
Cells { text: CellText, style: CellStyle },
}
/// The Text leaf a line breaker is asked to lay out.
#[derive(Clone, Copy, Debug)]
pub struct TextRequest<'a> {
pub node: &'a NodeId,
pub text: &'a str,
pub style_token: &'a str,
pub wrap: bool,
pub max_lines: Option<u32>,
}
/// One line: `y` and `height` are measured from the top of the node, in logical px or cells.
#[derive(Clone, Debug, PartialEq)]
pub struct TextLine {
pub y: f32,
pub height: f32,
pub run: Run,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TextLayout {
pub lines: Vec<TextLine>,
}
/// The intrinsic size `(width, height)` of a leaf under a constraint. A non-finite or negative
/// answer is taken as zero. `text` is the same engine's answer for a Text leaf at its final
/// width: the lines `measure` sized the leaf for, broken and shaped. Wrap and `max_lines` are the
/// engine's; render never breaks a line.
pub trait Measure {
fn measure(&mut self, leaf: &Leaf, constraint: Constraint) -> (f32, f32);
fn text(&mut self, request: &TextRequest, width: f32) -> TextLayout;
}
/// The largest length, in device px or cells, a style or a measure may state: 2^21 = 2,097,152.
/// f32 has 24 mantissa bits, so a coordinate below 2^24 is exact to a whole pixel and one below
/// 2^21 keeps 3 fractional bits, 1/8 px. A coordinate is a sum of lengths along an axis: eight
/// maximal siblings still sum below 2^24 (whole-pixel exact), and any run of siblings whose
/// extents sum below 2^21 keeps 1/8 px. A length beyond the bound is an invalid style value and a
/// larger measured size is clamped to it.
pub(crate) const MAX_DEVICE: f32 = 2_097_152.0;
/// The smallest nonzero extent a measure may state: 1/8 px, the precision the length bound
/// leaves. A smaller side is below the resolution layout keeps.
pub(super) const MIN_SIDE: f32 = 0.125;
/// The 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) }
}
/// A Plot's size: the CSS default object size, 300x150 logical px, or 38x10 cells. A plot is
/// sized by layout, never measured.
pub(super) fn plot(self) -> (f32, f32) {
if self.cells { (38.0, 10.0) } else { (self.px(300.0), self.px(150.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

@ -0,0 +1,216 @@
//! 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

@ -0,0 +1,56 @@
//! 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

@ -0,0 +1,289 @@
//! 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

@ -0,0 +1,295 @@
//! 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) {
// A plot declares no size: layout gives it the default object size.
let (width, height) = self.dev.plot();
let style = Style {
size: taffy::Size { width: taffy::Dimension::length(width), height: taffy::Dimension::length(height) },
..Style::default()
};
let index = self.entry(&n.common.id, parent, &Overflow::Visible);
let id = self.taffy.new_leaf(style).expect("taffy: insert");
self.entries[index].node = id;
out.push(id);
}
}
})
}
}

View file

@ -0,0 +1,16 @@
//! 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 frame;
pub mod input;
pub mod layout;
pub mod port;
pub mod render;
pub mod resolve;
pub mod text;
pub mod theme;
pub mod time;
pub use frame::{Config, Core, FrameInput, FrameOutput, Ports};

View file

@ -0,0 +1,53 @@
//! 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

@ -0,0 +1,146 @@
//! 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

@ -0,0 +1,26 @@
//! 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

@ -0,0 +1,37 @@
//! 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

@ -0,0 +1,174 @@
//! The leaves: control chrome, an Image's fit and the missing-asset placeholder. Core alone turns
//! fit and control state into geometry; no caret, selection or focus ring (those need edit and
//! focus state). Pixels and Cells share the lowering; only the inset and the stroke differ.
use thing_contract::{ButtonNode, ImageFit, ImageNode, NodeId, SelectNode, SliderNode, TextInputNode, ToggleNode};
use super::Painter;
use super::command::RenderCommand;
use crate::bind::{Bound, Field};
use crate::diagnostic::{Code, Diagnostic};
use crate::layout::{Measure, Metrics, Rect, TextRequest};
/// Where an Image lands inside `rect` for an extent of `(w, h)` asset px (1 asset px = 1 logical
/// px), and whether it must be clipped to `rect`.
fn fitted(fit: &ImageFit, rect: Rect, (w, h): (f32, f32)) -> (Rect, bool) {
let scale = match fit {
ImageFit::Fill => return (rect, false),
ImageFit::Contain => (rect.w / w).min(rect.h / h),
ImageFit::Cover => (rect.w / w).max(rect.h / h),
ImageFit::Unscaled => 1.0,
};
let (dw, dh) = (w * scale, h * scale);
let dest = Rect { x: rect.x + (rect.w - dw) / 2.0, y: rect.y + (rect.h - dh) / 2.0, w: dw, h: dh };
(dest, matches!(fit, ImageFit::Cover | ImageFit::Unscaled))
}
impl<'a> Painter<'a> {
fn flag(&self, id: &NodeId, field: Field) -> Option<bool> {
match self.tree.value(id, field) {
Some(Bound::Bool(b)) => Some(*b),
_ => None,
}
}
fn bound_text(&self, id: &NodeId, field: Field) -> Option<&'a str> {
let tree = self.tree;
match tree.value(id, field) {
Some(Bound::Text(t)) => Some(t.as_str()),
_ => None,
}
}
/// The inset of a control's content from its border: 2 logical px, none in a cell grid.
fn inset(&self) -> f32 {
if self.input.metrics == Metrics::Cells { 0.0 } else { 2.0 }
}
fn stroke(&mut self, id: &NodeId, rect: Rect) {
let color = self.named(id, "thing.control.border");
self.out.commands.push(RenderCommand::StrokeRect { rect, radius: 0.0, width: 1.0, color });
}
fn fill(&mut self, id: &NodeId, rect: Rect, token: &str) {
let color = self.named(id, token);
self.out.commands.push(RenderCommand::FillRect { rect, radius: 0.0, color });
}
/// The lines of `content` the engine breaks at `at.w`, those that end within `room` of the top.
#[allow(clippy::too_many_arguments)]
pub(super) fn draw_text(&mut self, id: &NodeId, content: &str, token: &str, wrap: bool, max_lines: Option<u32>, at: Rect, room: f32, text: &mut dyn Measure) {
let color = match self.input.theme.text.get(token) {
Some(style) => style.color.clone(),
None => self.fault(id, token),
};
let request = TextRequest { node: id, text: content, style_token: token, wrap, max_lines };
for line in text.text(&request, at.w).lines.into_iter().filter(|line| line.y + line.height <= room) {
self.out.commands.push(RenderCommand::Text { origin: (at.x, at.y + line.y), run: line.run, color: color.clone() });
}
}
/// What stands where a leaf's content could not be drawn: a fill and an error stroke.
pub(super) fn placeholder(&mut self, id: &NodeId, rect: Rect) {
self.fill(id, rect, "thing.placeholder");
let color = self.named(id, "thing.error");
self.out.commands.push(RenderCommand::StrokeRect { rect, radius: 0.0, width: 1.0, color });
}
/// The content box of a control: `rect` less the inset all round.
fn content_box(&self, rect: Rect) -> Rect {
let pad = self.inset().min(rect.w / 2.0).min(rect.h / 2.0).max(0.0);
Rect { x: rect.x + pad, y: rect.y + pad, w: rect.w - 2.0 * pad, h: rect.h - 2.0 * pad }
}
pub(super) fn button(&mut self, n: &ButtonNode, rect: Rect) {
let id = &n.common.id;
let enabled = self.flag(id, Field::Enabled) != Some(false);
self.fill(id, rect, if enabled { "thing.control.fill" } else { "thing.control.disabled" });
self.stroke(id, rect);
}
pub(super) fn toggle(&mut self, n: &ToggleNode, rect: Rect) {
let id = &n.common.id;
self.stroke(id, rect);
let inner = self.content_box(rect);
let side = inner.h.min(inner.w / 2.0).max(0.0);
let checked = self.flag(id, Field::Checked) == Some(true);
let x = if checked { inner.x + inner.w - side } else { inner.x };
self.fill(id, Rect { x, y: inner.y + (inner.h - side) / 2.0, w: side, h: side }, "thing.control.accent");
}
pub(super) fn slider(&mut self, n: &SliderNode, rect: Rect) {
let id = &n.common.id;
let thickness = if self.input.metrics == Metrics::Cells { rect.h } else { rect.h / 4.0 };
self.fill(id, Rect { x: rect.x, y: rect.y + (rect.h - thickness) / 2.0, w: rect.w, h: thickness }, "thing.control.border");
let fraction = if n.min.is_finite() && n.max.is_finite() && n.min < n.max {
match self.tree.value(id, Field::Value) {
Some(Bound::Number(v)) if v.is_finite() => ((v - n.min) / (n.max - n.min)).clamp(0.0, 1.0),
_ => 0.0,
}
} else {
self.out.diagnostics.push(Diagnostic {
code: Code::StyleValueInvalid,
surface: self.tree.resolved().document().record_key(),
node: Some(id.clone()),
detail: "max".to_string(),
});
0.0
};
let side = rect.h.min(rect.w).max(0.0);
let x = rect.x + (rect.w - side) * fraction as f32;
self.fill(id, Rect { x, y: rect.y, w: side, h: side }, "thing.control.accent");
}
pub(super) fn select(&mut self, n: &SelectNode, rect: Rect, text: &mut dyn Measure) {
let id = &n.common.id;
self.stroke(id, rect);
let Some(value) = self.bound_text(id, Field::Selected) else { return };
let tree = self.tree;
let label = match tree.value(id, Field::Options) {
Some(Bound::Options(options)) => options.iter().find(|o| o.value == value).map_or(value, |o| o.label.as_str()),
_ => value,
};
let inner = self.content_box(rect);
self.draw_text(id, label, "thing.text", false, Some(1), inner, inner.h, text);
}
pub(super) fn text_input(&mut self, n: &TextInputNode, rect: Rect, text: &mut dyn Measure) {
let id = &n.common.id;
self.stroke(id, rect);
let (content, token) = match self.bound_text(id, Field::Initial).filter(|t| !t.is_empty()) {
Some(initial) => (initial, "thing.text"),
None => match self.bound_text(id, Field::Placeholder) {
Some(placeholder) => (placeholder, "thing.text.placeholder"),
None => return,
},
};
let inner = self.content_box(rect);
self.draw_text(id, content, token, n.multiline, if n.multiline { None } else { Some(1) }, inner, inner.h, text);
}
pub(super) fn image(&mut self, n: &ImageNode, rect: Rect, text: &mut dyn Measure) {
let id = &n.common.id;
let alt = self.bound_text(id, Field::Alt).unwrap_or("");
let tree = self.tree;
let entry = match tree.value(id, Field::Asset) {
Some(Bound::Asset(entry)) if entry.width.get() > 0 && entry.height.get() > 0 => entry,
_ => {
self.placeholder(id, rect);
if !alt.is_empty() && rect.w > 0.0 {
self.draw_text(id, alt, "thing.text", true, Some(1), rect, rect.h, text);
}
return;
}
};
let (dest, clipped) = fitted(&n.fit, rect, (entry.width.get() as f32, entry.height.get() as f32));
if clipped {
self.out.commands.push(RenderCommand::ClipPush { rect, radius: 0.0 });
}
self.out.commands.push(RenderCommand::Image { rect: dest, uri: entry.uri.clone(), alt: alt.to_string() });
if clipped {
self.out.commands.push(RenderCommand::ClipPop);
}
}
}

View file

@ -0,0 +1,307 @@
//! Render: a `BoundTree`, its `LaidTree`, the scroll offsets and a theme become the closed command
//! list and the placed geometry hit-test, IME and accessibility read. A pure function: it reads
//! no port, no clock and no state, and equal inputs give an equal `Rendered`.
//!
//! This is the one place device px become logical px (divided by the scale) and scroll offsets
//! apply. Paint order is `LaidTree` order, which layout owns; render only looks nodes up.
mod command;
mod leaf;
mod plot;
mod scroll;
use std::collections::HashMap;
use thing_contract::{Anchor, BoxNode, ColorRef, Node, NodeId, Rgba};
pub use command::{RenderCommand, balanced};
pub use scroll::{ScrollOffsets, clamp};
use crate::bind::{Bound, BoundTree, Field};
use crate::diagnostic::{Code, Diagnostic};
use crate::layout::{LaidTree, MAX_DEVICE, Measure, Metrics, Rect};
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 }
}
pub(super) fn fault(&mut self, node: &NodeId, token: &str) -> Rgba {
self.out.diagnostics.push(Diagnostic {
code: Code::ThemeTokenUnknown,
surface: self.tree.resolved().document().record_key(),
node: Some(node.clone()),
detail: token.to_string(),
});
fallback()
}
fn color(&mut self, node: &NodeId, color: &ColorRef) -> Rgba {
match (self.input.theme.resolve(color), color) {
(Some(rgba), _) => rgba,
(None, ColorRef::Token(token)) => self.fault(node, &token.name),
(None, ColorRef::Rgba(literal)) => literal.clone(),
}
}
pub(super) fn named(&mut self, node: &NodeId, name: &str) -> Rgba {
match self.input.theme.color(name) {
Some(rgba) => rgba,
None => self.fault(node, name),
}
}
/// The border a Box draws: its colour and width, when it has a legal width.
fn border(&self, b: &'a BoxNode) -> Option<(&'a ColorRef, f32)> {
let border = b.paint.border.as_ref()?;
let width = border.width as f32;
(width.is_finite() && width > 0.0 && width * self.k <= MAX_DEVICE).then_some((&border.color, width))
}
fn enter(&mut self, i: usize, text: &mut dyn Measure) {
let tree = self.laid;
let laid = &tree.nodes[i];
let parent = laid.parent.map(|p| p as usize);
while let Some(&top) = self.stack.last() {
if Some(top) == parent {
break;
}
self.stack.pop();
self.close(top);
}
let node = self.nodes.get(&laid.id).copied();
let shift = match (parent, node) {
(Some(p), _) => self.inner[p],
// An overlay root is carried by what its anchor is carried by, never by the anchor's own scroll.
(None, Some(Node::Overlay(o))) => match &o.anchor {
Anchor::Node(anchor) => match self.ids.get(&anchor.node) {
Some(&a) if a < i => self.shift[a],
_ => (0.0, 0.0),
},
Anchor::Viewport => (0.0, 0.0),
},
(None, _) => (0.0, 0.0),
};
let own = self.input.scroll.of(laid);
self.shift.push(shift);
self.inner.push((shift.0 - own.0, shift.1 - own.1));
let rect = self.logical(laid.rect, shift);
let visible = self.clips.iter().try_fold(rect, |seen, clip| meet(seen, *clip));
self.out.placed.push(Placed { id: laid.id.clone(), rect, visible });
self.stack.push(i);
let Some(node) = node else { return };
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) => self.placeholder(&u.common.id, rect),
Node::Text(n) => {
let tree = self.tree;
match tree.value(&n.common.id, Field::Content) {
Some(Bound::Text(content)) => {
let max_lines = n.max_lines.map(|lines| lines.get().max(0) as u32);
self.draw_text(&n.common.id, content, &n.style_token, n.wrap, max_lines, rect, f32::INFINITY, text);
}
Some(Bound::Error(_)) => {
let color = self.named(&n.common.id, "thing.error");
self.out.commands.push(RenderCommand::StrokeRect { rect, radius: 0.0, width: 1.0, color });
}
_ => {}
}
}
Node::Button(n) => self.button(n, rect),
Node::Toggle(n) => self.toggle(n, rect),
Node::Slider(n) => self.slider(n, rect),
Node::Select(n) => self.select(n, rect, text),
Node::TextInput(n) => self.text_input(n, rect, text),
Node::Image(n) => self.image(n, rect, text),
Node::Plot(n) => self.plot(n, rect),
Node::Overlay(_) | Node::Repeat(_) | Node::Slot(_) => {}
}
}
/// Close an open node: its clip, then its scrollbars (which the clip does not cut).
fn close(&mut self, i: usize) {
let laid = self.laid;
let node = &laid.nodes[i];
let Some(padding) = node.clip else { 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

@ -0,0 +1,173 @@
//! A Plot lowered to geometry: the domain, then Polylines, Polygons or FillRects. Pure and
//! bounded: a series of N points gives at most N vertices (Line), 2N (Area: each run of m >= 2
//! points adds two baseline vertices) or N rects (Bar); a non-finite or unrepresentable (f32) point is skipped with one diagnostic, never drawn.
use thing_contract::{PlotMark, PlotNode};
use super::Painter;
use super::command::RenderCommand;
use crate::bind::{Bound, Field};
use crate::diagnostic::{Code, Diagnostic};
use crate::layout::Rect;
/// One axis' domain: an explicit bound that is finite and not crossed by the other end is kept,
/// anything else takes the data value and is named; equal ends widen by 1 each way.
fn domain(explicit: (Option<f64>, Option<f64>), data: (f64, f64), names: (&'static str, &'static str), invalid: &mut Vec<&'static str>) -> (f64, f64) {
let (mut lo, mut hi) = (explicit.0.filter(|v| v.is_finite()), explicit.1.filter(|v| v.is_finite()));
if explicit.0.is_some() && lo.is_none() {
invalid.push(names.0);
}
if explicit.1.is_some() && hi.is_none() {
invalid.push(names.1);
}
if let (Some(a), Some(b)) = (lo, hi) {
if a > b {
invalid.extend([names.0, names.1]);
(lo, hi) = (None, None);
}
} else if let Some(a) = lo {
if a > data.1 {
invalid.push(names.0);
lo = None;
}
} else if let Some(b) = hi {
if b < data.0 {
invalid.push(names.1);
hi = None;
}
}
let (lo, hi) = (lo.unwrap_or(data.0), hi.unwrap_or(data.1));
if lo == hi { (lo - 1.0, hi + 1.0) } else { (lo, hi) }
}
/// Where the series lands in `rect`: screen y grows down.
struct Frame {
rect: Rect,
x: (f64, f64),
y: (f64, f64),
}
impl Frame {
/// A point of the series as f32 screen coordinates, `None` when either does not fit an f32.
fn at(&self, i: usize, v: f64) -> Option<(f32, f32)> {
let tx = halved(i as f64, self.x);
let x = (self.rect.x as f64 + tx * self.rect.w as f64) as f32;
let y = self.value(v) as f32;
(x.is_finite() && y.is_finite()).then_some((x, y))
}
/// Screen y of a value: y grows down. Halves keep a span near f64's range from overflowing.
fn value(&self, v: f64) -> f64 {
self.rect.y as f64 + self.rect.h as f64 - halved(v, self.y) * self.rect.h as f64
}
}
/// Where `v` falls in `(lo, hi)`, 0 to 1, computed on halves so `hi - lo` cannot overflow.
fn halved(v: f64, (lo, hi): (f64, f64)) -> f64 {
(v / 2.0 - lo / 2.0) / (hi / 2.0 - lo / 2.0)
}
impl Painter<'_> {
pub(super) fn plot(&mut self, n: &thing_contract::PlotNode, rect: Rect) {
let tree = self.tree;
match tree.value(&n.common.id, Field::Series) {
Some(Bound::Series(values)) => self.plot_series(n, values, rect),
Some(Bound::Error(_)) => self.placeholder(&n.common.id, rect),
_ => {}
}
}
/// A point that was not drawn is said once for the plot, whatever the reason.
fn dropped(&mut self, n: &PlotNode) {
self.out.diagnostics.push(Diagnostic {
code: Code::StyleValueInvalid,
surface: self.tree.resolved().document().record_key(),
node: Some(n.common.id.clone()),
detail: "series".to_string(),
});
}
fn plot_series(&mut self, n: &PlotNode, values: &[f64], rect: Rect) {
if values.is_empty() || !(rect.w > 0.0 && rect.h > 0.0) {
return;
}
let finite = || values.iter().copied().filter(|v| v.is_finite());
let low = finite().fold(f64::INFINITY, f64::min);
let high = finite().fold(f64::NEG_INFINITY, f64::max);
let data_y = if low <= high { (low, high) } else { (0.0, 0.0) };
let mut invalid = Vec::new();
let x = domain((n.x_min, n.x_max), (0.0, (values.len() - 1) as f64), ("x_min", "x_max"), &mut invalid);
let y = domain((n.y_min, n.y_max), data_y, ("y_min", "y_max"), &mut invalid);
for name in invalid {
self.out.diagnostics.push(Diagnostic {
code: Code::StyleValueInvalid,
surface: self.tree.resolved().document().record_key(),
node: Some(n.common.id.clone()),
detail: name.to_string(),
});
}
let frame = Frame { rect, x, y };
let color = self.named(&n.common.id, "thing.plot.mark");
let width = match self.input.metrics {
crate::layout::Metrics::Cells => 1.0,
crate::layout::Metrics::Pixels => 2.0,
};
let base = frame.value(0.0f64.clamp(y.0, y.1));
if !(base as f32).is_finite() {
self.dropped(n);
return;
}
let mut shapes = Vec::new();
let mut dropped = false;
match n.mark {
PlotMark::Bar => {
let slot = rect.w / values.len() as f32;
for (i, v) in values.iter().enumerate() {
let top = frame.value(*v);
let (y0, y1) = (top.min(base) as f32, top.max(base) as f32);
let bar = Rect { x: rect.x + slot * i as f32, y: y0, w: slot, h: y1 - y0 };
if v.is_finite() && [bar.x, bar.y, bar.w, bar.h].iter().all(|c| c.is_finite()) {
shapes.push(RenderCommand::FillRect { rect: bar, radius: 0.0, color: color.clone() });
} else {
dropped = true;
}
}
}
PlotMark::Line | PlotMark::Area => {
let mut run: Vec<(f32, f32)> = Vec::new();
let flush = |run: &mut Vec<(f32, f32)>, shapes: &mut Vec<RenderCommand>| {
if run.len() >= 2 {
let mut points = std::mem::take(run);
if n.mark == PlotMark::Area {
let (first, last) = (points[0].0, points[points.len() - 1].0);
points.extend([(last, base as f32), (first, base as f32)]);
shapes.push(RenderCommand::Polygon { points, color: color.clone() });
} else {
shapes.push(RenderCommand::Polyline { points, width, color: color.clone() });
}
}
run.clear();
};
for (i, v) in values.iter().enumerate() {
match v.is_finite().then(|| frame.at(i, *v)).flatten() {
Some(point) => run.push(point),
None => {
dropped = true;
flush(&mut run, &mut shapes);
}
}
}
flush(&mut run, &mut shapes);
}
}
if dropped {
self.dropped(n);
}
if shapes.is_empty() {
return;
}
self.out.commands.push(RenderCommand::ClipPush { rect, radius: 0.0 });
self.out.commands.extend(shapes);
self.out.commands.push(RenderCommand::ClipPop);
}
}

View file

@ -0,0 +1,38 @@
//! 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

@ -0,0 +1,597 @@
//! 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

@ -0,0 +1,165 @@
//! The Resolver: per surface, the highest version offered, the last good tree and the composition
//! interests that tree's resolution read. It is handed the changes the frame owner drained and
//! never drains itself. Every re-resolve reads the port again; no composition is cached here. The
//! interests are held through the shared `Ledger`, so the Binder and the Resolver count one
//! subscription per address.
use std::collections::{HashMap, HashSet};
use thing_contract::{DatabaseEntry, SurfaceDocument, Version};
use super::{Limits, ResolvedTree, resolve};
use crate::diagnostic::{Code, Diagnostic};
use crate::port::{Address, Change, Interest, Ledger, Record, StatePort};
/// What the Resolver holds of one surface.
struct Held {
/// The highest version offered, accepted or refused: the only one resolved again.
document: SurfaceDocument,
/// The last tree a resolve produced for a version above every earlier one.
tree: Option<ResolvedTree>,
/// The interests of the last resolve, which was of `document`.
interests: HashSet<Interest>,
/// Versions already reported stale.
reported: HashSet<Version>,
}
/// What one `apply` did: its diagnostics, and each surface key whose displayed tree it replaced
/// (`true`) or dropped (`false`), sorted by key. A re-resolve that failed keeps its tree and is
/// not listed, so the frame owner never infers a change by comparing trees.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Intake {
pub diagnostics: Vec<Diagnostic>,
pub changed: Vec<(String, bool)>,
}
pub struct Resolver {
limits: Limits,
surfaces: HashMap<String, Held>,
}
fn is_surface(address: &Address) -> bool {
address.schema.as_str() == SurfaceDocument::SCHEMA_NAME
}
impl Resolver {
pub fn new(limits: Limits) -> Self {
Self { limits, surfaces: HashMap::new() }
}
/// The tree displayed for a surface key: the last good one.
pub fn tree(&self, surface_key: &str) -> Option<&ResolvedTree> {
self.surfaces.get(surface_key).and_then(|held| held.tree.as_ref())
}
/// Drop a surface the consumer no longer shows: its interests are released and its entry goes
/// with no tombstone (the consumer leaving is not the provider deleting).
pub fn forget(&mut self, surface_key: &str, port: &mut dyn StatePort, ledger: &mut Ledger) {
if let Some(held) = self.surfaces.remove(surface_key) {
ledger.diff(port, &held.interests, &HashSet::new());
}
}
/// One drained change. A surface offer is judged by the version rule; a change at a
/// composition a held surface read resolves that surface again from its held document.
pub fn apply(&mut self, change: &Change, port: &mut dyn StatePort, ledger: &mut Ledger) -> Intake {
let address = match change {
Change::Upsert(entry) => &entry.address,
Change::Delete(address) => address,
Change::Refused(refusal) => &refusal.address,
};
if is_surface(address) {
return match change {
Change::Upsert(entry) => match &entry.record {
Record::Surface(document) => self.offer(document, port, ledger),
_ => Intake::default(),
},
Change::Delete(address) => {
// A tombstone: the highest version stays so an older one is not taken again,
// but the tree and the interests go.
let mut changed = Vec::new();
if let Some(held) = self.surfaces.get_mut(address.key.as_str()) {
if held.tree.take().is_some() {
changed.push((address.key.as_str().to_string(), false));
}
let released = std::mem::take(&mut held.interests);
ledger.diff(port, &released, &HashSet::new());
}
Intake { diagnostics: Vec::new(), changed }
}
Change::Refused(refusal) => Intake {
diagnostics: vec![Diagnostic {
code: Code::DecodeRefused,
surface: address.key.as_str().to_string(),
node: None,
detail: refusal.detail.clone(),
}],
changed: Vec::new(),
},
};
}
let mut readers: Vec<String> = self
.surfaces
.iter()
.filter(|(_, held)| held.interests.iter().any(|interest| interest.matches(address)))
.map(|(key, _)| key.clone())
.collect();
readers.sort();
let mut intake = Intake::default();
for key in readers {
let document = self.surfaces[&key].document.clone();
let (diagnostics, replaced) = self.resolve_held(&key, document, port, ledger);
intake.diagnostics.extend(diagnostics);
if replaced {
intake.changed.push((key, true));
}
}
intake
}
fn offer(&mut self, document: &SurfaceDocument, port: &mut dyn StatePort, ledger: &mut Ledger) -> Intake {
let key = document.record_key();
if let Some(held) = self.surfaces.get_mut(&key)
&& document.version <= held.document.version
{
// A subscribe replays the current record: the same document again is not news.
let diagnostics = if document.version == held.document.version && *document == held.document {
Vec::new()
} else if held.reported.insert(document.version) {
vec![Diagnostic {
code: Code::StaleVersionIgnored,
surface: key,
node: None,
detail: "version at or below the held version, which stays".into(),
}]
} else {
Vec::new()
};
return Intake { diagnostics, changed: Vec::new() };
}
let (diagnostics, replaced) = self.resolve_held(&key, document.clone(), port, ledger);
Intake { diagnostics, changed: if replaced { vec![(key, true)] } else { Vec::new() } }
}
/// Resolve `document` as the highest offered for `key`: a tree replaces the held one, no tree
/// keeps it. The interests become the reads either way. The flag is whether a tree replaced
/// the held one.
fn resolve_held(&mut self, key: &str, document: SurfaceDocument, port: &mut dyn StatePort, ledger: &mut Ledger) -> (Vec<Diagnostic>, bool) {
let resolution = resolve(&document, &*port, &self.limits);
let interests: HashSet<Interest> = resolution.reads.into_iter().map(Interest::Record).collect();
let held = self.surfaces.entry(key.to_string()).or_insert_with(|| Held {
document: document.clone(),
tree: None,
interests: HashSet::new(),
reported: HashSet::new(),
});
ledger.diff(port, &held.interests, &interests);
held.interests = interests;
held.document = document;
let replaced = resolution.tree.is_some();
if let Some(tree) = resolution.tree {
held.tree = Some(tree);
}
(resolution.diagnostics, replaced)
}
}

View file

@ -0,0 +1,111 @@
//! Resolve: the pure expansion of a surface document into a tree with no composition left in it.
//! This is the only code that reads Thing Script structure (Use, Param, CommandRef, node ids).
//! It reads compositions through `StatePort::read` and `thing.std` from a compiled-in table,
//! holds no state, subscribes to nothing and never drains; `Resolver` is the stateful half.
mod expand;
mod intake;
pub mod std;
mod validate;
use thing_contract::SurfaceDocument;
pub use intake::{Intake, Resolver};
use crate::diagnostic::{Code, Diagnostic};
use crate::port::{Address, StatePort};
/// Stack left below which recursion moves to a fresh segment, and the segment's size: the values
/// cultcache-rs uses for decode. Every recursion over a tree runs through `grow`, so a tree as deep
/// as `STACK_BOUND` resolves on a default thread.
const RED_ZONE: usize = 512 * 1024;
const SEGMENT: usize = 2 * 1024 * 1024;
/// Runs one recursive step with room for the next, growing the stack when it is nearly spent.
pub(crate) fn grow<R>(step: impl FnOnce() -> R) -> R {
stacker::maybe_grow(RED_ZONE, SEGMENT, step)
}
/// The bounds of one expansion.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Limits {
/// Compositions nested in one another; a Use deeper than this is a placeholder.
pub max_use_depth: usize,
/// The contract's decode bound; a deeper expanded tree is refused.
pub max_tree_depth: usize,
/// Nodes in the expanded tree; more is refused.
pub max_nodes: usize,
}
impl Default for Limits {
fn default() -> Self {
Self { max_use_depth: 32, max_tree_depth: 256, max_nodes: 65_536 }
}
}
/// A surface document expanded: no Param of any kind remains, every command is declared, every
/// state reference names its provider, node ids are unique, and a Use remains only as a
/// placeholder leaf (its arguments emptied) beside a diagnostic. Only `resolve` builds one.
#[derive(Clone, Debug, PartialEq)]
pub struct ResolvedTree {
document: SurfaceDocument,
}
impl ResolvedTree {
pub fn document(&self) -> &SurfaceDocument {
&self.document
}
}
/// What one expansion found. `tree` is `None` when a fault refuses the whole document.
#[derive(Clone, Debug, PartialEq)]
pub struct Resolution {
pub tree: Option<ResolvedTree>,
/// Expansion faults in expansion pre-order, then the finished tree's faults (duplicate ids, depth)
/// in tree pre-order.
pub diagnostics: Vec<Diagnostic>,
/// Every non-std composition address consulted, whether present, absent or refused, once each, ordered
/// by provider, schema and key.
pub reads: Vec<Address>,
}
pub fn resolve(document: &SurfaceDocument, port: &dyn StatePort, limits: &Limits) -> Resolution {
let mut expander = expand::Expander::new(document, port, limits);
let root = match expander.root(&document.root) {
Ok(root) => Some(root),
Err(expand::Fault::Limit(detail)) => {
expander.diag(Code::ExpansionLimit, None, detail);
None
}
Err(expand::Fault::Stack(detail)) => {
expander.diag(Code::TooDeepToResolve, None, detail);
None
}
Err(expand::Fault::Invalid(detail)) => {
expander.diag(Code::CompositionInvalid, None, detail);
None
}
};
let mut diagnostics = ::std::mem::take(&mut expander.diagnostics);
let mut reads: Vec<Address> = ::std::mem::take(&mut expander.reads).into_iter().collect();
reads.sort_by(|a, b| {
let key = |address: &Address| (address.provider.as_str().to_string(), address.schema.as_str().to_string(), address.key.as_str().to_string());
key(a).cmp(&key(b))
});
let tree = root.and_then(|root| {
diagnostics.extend(validate::check(&root, 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

@ -0,0 +1,95 @@
//! `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

@ -0,0 +1,110 @@
//! 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

@ -0,0 +1,317 @@
//! The Cells text engine: `CellText` is the one constructor of terminal text and `CellMeasure` the
//! one `Measure` for Cells. Every width and every break a cell backend advances by is decided
//! here, per extended grapheme cluster, and no backend computes either.
//!
//! Order is sanitize, then segment and measure: the text is cleaned (controls become U+FFFD,
//! clusters without width are dropped) until segmenting it again changes nothing, so every width
//! recorded is the width of exactly the text a terminal receives.
//!
//! Breaking is CSS `white-space: pre-wrap` with `overflow-wrap: break-word`: mandatory breaks
//! always break, soft breaks are UAX #14 Allowed positions on a cluster boundary, trailing spaces
//! at a soft break hang (are not emitted), and an unbreakable segment wider than the line breaks
//! between clusters. A line takes at least one cluster, so at width 0 every cluster sits on its
//! own line. Text is laid out in logical order; bidi reordering is Pixels-only.
use unicode_linebreak::{BreakOpportunity, linebreaks};
use unicode_segmentation::UnicodeSegmentation;
use unicode_width::UnicodeWidthStr;
use crate::bind::Bound;
use crate::layout::{Avail, CellStyle, Constraint, Leaf, Measure, Run, TextLayout, TextLine, TextRequest};
/// The tab stop, in columns (CSS `tab-size: 8`).
const TAB: u32 = 8;
/// Terminal text: a string with one width per extended grapheme cluster, free of control
/// characters and of zero-width clusters, whose clusters re-segment to themselves. A document
/// never writes an escape code into a terminal because no other constructor exists.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CellText {
text: String,
/// The end byte offset and the width in cells of each cluster, in order.
clusters: Vec<(u32, u8)>,
}
impl CellText {
/// One line of terminal text. Tabs stop at multiples of 8 columns from the start of `text`;
/// every control character, line terminators included, becomes U+FFFD (width 1); a cluster
/// without width is dropped.
pub fn new(text: &str) -> Self {
let (clean, open) = clean(text);
emit(&atoms(&clean, &open))
}
pub fn as_str(&self) -> &str {
&self.text
}
/// Each cluster with its width in cells.
pub fn clusters(&self) -> impl Iterator<Item = (&str, u8)> {
let mut start = 0;
self.clusters.iter().map(move |&(end, width)| {
let cluster = &self.text[start as usize..end as usize];
start = end as usize;
(cluster, width)
})
}
/// The width of the line in cells: the sum of its cluster widths.
pub fn width(&self) -> u32 {
self.clusters.iter().map(|&(_, w)| u32::from(w)).sum()
}
}
/// One kept cluster of a paragraph and whether a soft break may precede it. A tab is an atom of
/// its own: its width is decided where it falls in a line.
struct Atom<'a> {
text: &'a str,
width: u8,
tab: bool,
space: bool,
open: bool,
}
impl Atom<'_> {
/// The columns this atom takes when it starts at `column` of its line.
fn cols(&self, column: u32) -> u32 {
if self.tab { TAB - column % TAB } else { u32::from(self.width) }
}
}
fn is_terminator(c: char) -> bool {
matches!(c, '\n' | '\r' | '\u{b}' | '\u{c}' | '\u{85}' | '\u{2028}' | '\u{2029}')
}
/// Sanitize, to a fixpoint: every control (a tab excepted) becomes U+FFFD and every cluster
/// without width is dropped, and since either can change how the rest segments, the result is
/// segmented again until nothing more changes. Returns the text and, by byte offset, where a soft
/// break may fall; the opportunity at a dropped cluster rides on the next kept one.
fn clean(paragraph: &str) -> (String, Vec<bool>) {
let mut open = vec![false; paragraph.len() + 1];
for (at, kind) in linebreaks(paragraph) {
if kind == BreakOpportunity::Allowed {
open[at] = true;
}
}
let mut text = paragraph.to_owned();
loop {
let mut out = String::with_capacity(text.len());
let mut marks = Vec::new();
let (mut pending, mut changed) = (false, false);
for (start, cluster) in text.grapheme_indices(true) {
let here = open[start] || pending;
pending = false;
let first = cluster.chars().next().expect("a cluster has a scalar");
let kept = if cluster == "\t" {
cluster
} else if first.is_control() || is_terminator(first) {
changed = true;
"\u{fffd}"
} else if cluster.width() == 0 {
(pending, changed) = (here, true);
continue;
} else {
cluster
};
if here {
marks.push(out.len());
}
out.push_str(kept);
}
if !changed {
return (text, open);
}
open = vec![false; out.len() + 1];
for mark in marks {
open[mark] = true;
}
text = out;
}
}
/// The clusters of cleaned text.
fn atoms<'a>(text: &'a str, open: &[bool]) -> Vec<Atom<'a>> {
let mut out: Vec<Atom> = text
.grapheme_indices(true)
.map(|(start, cluster)| {
let tab = cluster == "\t";
Atom { text: cluster, width: if tab { 0 } else { cluster.width().min(255) as u8 }, tab, space: tab || cluster == " ", open: open[start] }
})
.collect();
if let Some(first) = out.first_mut() {
first.open = false;
}
out
}
/// One line as terminal text: tabs become spaces to the next stop from the line's start, and the
/// result is cleaned and segmented once more, so its recorded widths are those of the emitted text.
fn emit(line: &[Atom]) -> CellText {
let mut text = String::new();
let mut column = 0;
for atom in line {
let cols = atom.cols(column);
if atom.tab {
text.extend(std::iter::repeat_n(' ', cols as usize));
} else {
text.push_str(atom.text);
}
column += cols;
}
let (text, _) = clean(&text);
let mut out = CellText::default();
for cluster in text.graphemes(true) {
out.text.push_str(cluster);
out.clusters.push((out.text.len() as u32, cluster.width().min(255) as u8));
}
out
}
/// The paragraphs of `text`: the pieces between mandatory breaks, terminators removed. A final
/// terminator ends the last line and starts no empty one.
fn paragraphs(text: &str) -> Vec<&str> {
let mut out = Vec::new();
let mut from = 0;
for (at, kind) in linebreaks(text) {
if kind == BreakOpportunity::Mandatory && at < text.len() {
out.push(strip_terminator(&text[from..at]));
from = at;
}
}
out.push(strip_terminator(&text[from..]));
out
}
fn strip_terminator(piece: &str) -> &str {
match piece.graphemes(true).next_back() {
Some(last) if last.chars().any(is_terminator) => &piece[..piece.len() - last.len()],
_ => piece,
}
}
/// The lines of `text` at `cols` columns. `wrap` off breaks at mandatory breaks only.
fn break_lines(text: &str, wrap: bool, max_lines: Option<u32>, cols: u32) -> Vec<CellText> {
let cap = max_lines.map_or(usize::MAX, |n| n as usize);
let mut lines = Vec::new();
for paragraph in paragraphs(text) {
let (clean, open) = clean(paragraph);
let atoms = atoms(&clean, &open);
let mut start = 0;
loop {
if lines.len() >= cap {
return lines;
}
let end = if wrap { fit(&atoms, start, cols) } else { atoms.len() };
let mut line = &atoms[start..end];
if end < atoms.len() && line.iter().any(|a| !a.space) {
// A soft break: the spaces before it hang.
while let Some((last, rest)) = line.split_last() {
if !last.space {
break;
}
line = rest;
}
}
lines.push(emit(line));
if end >= atoms.len() {
break;
}
start = end;
}
}
lines
}
/// Where the line that starts at `start` ends: the last soft break that fits, else the last
/// cluster that fits, else (a cluster wider than the room) just that cluster. Spaces hang: they
/// never overflow a line.
fn fit(atoms: &[Atom], start: usize, cols: u32) -> usize {
let (mut width, mut shown) = (0u32, 0u32);
let mut candidate = None;
for (i, atom) in atoms.iter().enumerate().skip(start) {
if atom.open && i > start {
candidate = Some(i);
}
width += atom.cols(width);
if !atom.space {
shown = width;
if shown > cols && i > start {
return candidate.unwrap_or(i);
}
}
}
atoms.len()
}
/// The widest unbreakable segment, trailing spaces excluded.
fn longest_segment(text: &str) -> u32 {
let mut widest = 0;
for paragraph in paragraphs(text) {
let (clean, open) = clean(paragraph);
let (mut column, mut from, mut shown) = (0, 0, 0);
for atom in atoms(&clean, &open) {
if atom.open {
widest = widest.max(shown - from);
(from, shown) = (column, column);
}
column += atom.cols(column);
if !atom.space {
shown = column;
}
}
widest = widest.max(shown - from);
}
widest
}
fn lines_for(text: &str, wrap: bool, max_lines: Option<u32>, room: Avail) -> Vec<CellText> {
let cols = match room {
// `as` saturates: negative and NaN are 0, huge is u32::MAX.
Avail::Definite(w) if wrap => w.floor() as u32,
_ => u32::MAX,
};
break_lines(text, wrap, max_lines, cols)
}
/// The shipped Cells engine: text by cluster width and UAX #14, controls at fixed cell sizes.
#[derive(Clone, Copy, Debug, Default)]
pub struct CellMeasure;
impl Measure for CellMeasure {
fn measure(&mut self, leaf: &Leaf, c: Constraint) -> (f32, f32) {
match leaf {
Leaf::Text { content, wrap, max_lines, .. } => {
let text = match content {
Bound::Text(text) => text.as_str(),
_ => "",
};
let room = c.known[0].map(Avail::Definite).unwrap_or(c.available[0]);
if *wrap && room == Avail::MinContent {
let rows = lines_for(text, true, *max_lines, Avail::MaxContent).len();
return (longest_segment(text) as f32, rows as f32);
}
let lines = lines_for(text, *wrap, *max_lines, room);
(lines.iter().map(CellText::width).max().unwrap_or(0) as f32, lines.len() as f32)
}
Leaf::TextInput { multiline, .. } => (25.0, if *multiline { 3.0 } else { 1.0 }),
Leaf::Toggle { .. } => (5.0, 1.0),
Leaf::Slider { .. } => (20.0, 1.0),
Leaf::Select { .. } => (20.0, 1.0),
Leaf::Image { asset, .. } => match asset {
Bound::Asset(entry) => ((entry.width.get() as f32 / 8.0).ceil(), (entry.height.get() as f32 / 16.0).ceil()),
_ => (0.0, 0.0),
},
}
}
fn text(&mut self, request: &TextRequest, width: f32) -> TextLayout {
let lines = lines_for(request.text, request.wrap, request.max_lines, Avail::Definite(width));
TextLayout {
lines: lines
.into_iter()
.enumerate()
.map(|(row, text)| TextLine { y: row as f32, height: 1.0, run: Run::Cells { text, style: CellStyle::default() } })
.collect(),
}
}
}

View file

@ -0,0 +1,6 @@
//! Terminal text: what a string is made of in a cell grid. The one owner of every Cells width and
//! line break (Pixels text is the shaper's, behind the same `Measure` seam).
mod cells;
pub use cells::{CellMeasure, CellText};

View file

@ -0,0 +1,86 @@
//! The theme a frame is drawn with: named colours and named text styles, resolved to literals
//! in render so a token never reaches a backend. Where a host's theme comes from is
//! `thing2:follow_up:theme-record-contract`; render takes a `&Theme`.
use std::collections::BTreeMap;
use thing_contract::{ColorRef, Rgba};
use crate::layout::CellStyle;
/// What a text style token draws as: the colour render emits, and the size and cell attributes
/// the text engine reads when it shapes the line.
#[derive(Clone, Debug, PartialEq)]
pub struct TextStyle {
pub color: Rgba,
pub size: f32,
pub cells: CellStyle,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Theme {
pub colors: BTreeMap<String, Rgba>,
pub text: BTreeMap<String, TextStyle>,
/// Scrollbar thickness, logical px (one cell in Cells).
pub scrollbar: f32,
}
/// The colour a token the theme does not hold draws as, so the fault is visible.
pub fn fallback() -> Rgba {
Rgba { r: 0xff, g: 0x00, b: 0xff, a: 0xff }
}
fn rgba(hex: u32) -> Rgba {
Rgba { r: (hex >> 24) as u8, g: (hex >> 16) as u8, b: (hex >> 8) as u8, a: hex as u8 }
}
impl Theme {
/// `thing.std`'s default: every token render and the fixtures use.
pub fn std() -> Self {
let colors = [
("thing.surface", 0x1e1e2eff),
("thing.error", 0xe5484dff),
("thing.placeholder", 0x6e6e80ff),
("thing.scrim", 0x00000099),
("thing.scrollbar.thumb", 0xffffff66),
("thing.control.fill", 0x2c2c3eff),
("thing.control.border", 0x4a4a60ff),
("thing.control.accent", 0x7c9cffff),
("thing.control.text", 0xeeeef4ff),
("thing.control.disabled", 0x3a3a48ff),
("thing.plot.mark", 0x7c9cffff),
]
.into_iter()
.map(|(name, hex)| (name.to_string(), rgba(hex)))
.collect();
let style = |hex: u32, size: f32, bold: bool| TextStyle {
color: rgba(hex),
size,
cells: CellStyle { bold, ..CellStyle::default() },
};
let text = [
("title", style(0xffffffff, 24.0, true)),
("body", style(0xeeeef4ff, 16.0, false)),
("thing.text", style(0xeeeef4ff, 16.0, false)),
("thing.text.placeholder", style(0x6e6e80ff, 16.0, false)),
]
.into_iter()
.map(|(name, style)| (name.to_string(), style))
.collect();
Self { colors, text, scrollbar: 6.0 }
}
/// The literal a colour is: a token the theme holds, or the literal itself. `None` is an
/// unknown token.
pub fn resolve(&self, color: &ColorRef) -> Option<Rgba> {
match color {
ColorRef::Rgba(literal) => Some(literal.clone()),
ColorRef::Token(token) => self.colors.get(&token.name).cloned(),
}
}
/// A named colour of the theme's own (render's scrim, error and thumb).
pub fn color(&self, name: &str) -> Option<Rgba> {
self.colors.get(name).cloned()
}
}

View file

@ -0,0 +1,5 @@
//! Wall time as core is told it: the host reads its clock and hands core the reading.
/// Unix milliseconds, UTC.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Timestamp(pub i64);

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,260 @@
//! The Cells text engine: pinned widths, sanitizing, wrapping, and that `measure` and `text`
//! agree. Vectors were checked against unicode-width 0.2.3 (ambiguous width narrow).
use thing_contract::{AssetEntry, NodeId};
use thing_core::bind::Bound;
use thing_core::layout::{Avail, Constraint, Leaf, Measure, Run, TextRequest};
use thing_core::text::{CellMeasure, CellText};
use thing_testkit::build::count;
fn widths(s: &str) -> Vec<u8> {
CellText::new(s).clusters().map(|(_, w)| w).collect()
}
#[test]
fn width_vectors() {
let vectors: &[(&str, &[u8])] = &[
("a", &[1]),
("\u{4e2d}", &[2]),
("\u{ff21}", &[2]),
("\u{d55c}", &[2]),
("e\u{301}", &[1]),
("\u{b1}", &[1]),
("\u{3b1}", &[1]),
("\u{1f600}", &[2]),
("\u{2764}", &[1]),
("\u{2764}\u{fe0f}", &[2]),
("\u{263a}\u{fe0e}", &[1]),
("\u{1f44d}\u{1f3fd}", &[2]),
("\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}", &[2]),
("\u{1f1ef}\u{1f1f5}", &[2]),
("\u{1f1ef}", &[1]),
("1\u{fe0f}\u{20e3}", &[2]),
("\u{1f3f3}\u{fe0f}\u{200d}\u{1f308}", &[2]),
("\u{1100}\u{1161}\u{11a8}", &[2]),
("\u{915}\u{94d}\u{937}", &[2]),
("\u{e01}\u{e33}", &[2]),
("\u{17d8}", &[3]),
("\u{a0}", &[1]),
("\u{644}\u{627}", &[1, 1]),
];
for (text, expected) in vectors {
assert_eq!(&widths(text), expected, "{text:?}");
assert_eq!(CellText::new(text).width(), expected.iter().map(|&w| u32::from(w)).sum::<u32>(), "{text:?} line width is the cluster sum");
}
}
#[test]
fn sanitizing() {
for c in ['\u{1b}', '\u{7f}', '\u{9b}'] {
let s = c.to_string();
assert_eq!((CellText::new(&s).as_str(), widths(&s)), ("\u{fffd}", vec![1]), "{c:?}");
}
assert_eq!(CellText::new("a\tb").as_str(), "a b");
assert_eq!(CellText::new("abcdefgh\ti").as_str(), "abcdefgh i");
for vanishing in ["\u{202e}", "\u{200b}", "\u{ad}", "\u{200d}", "\u{301}"] {
assert_eq!(CellText::new(vanishing).as_str(), "", "{vanishing:?}");
}
assert_eq!(CellText::new("\u{301}a").as_str(), "a");
assert_eq!(CellText::new("x\u{200b}y").as_str(), "xy");
// The break opportunity of a dropped cluster survives.
assert_eq!(lines("x\u{200b}y", 1), ["x", "y"]);
// A terminator handed straight to `new` is a control like any other.
assert_eq!(CellText::new("a\nb").as_str(), "a\u{fffd}b");
assert_eq!(CellText::new("a\u{2028}b").as_str(), "a\u{fffd}b");
assert_eq!(widths("a\u{2028}b"), [1, 1, 1]);
}
#[test]
fn dropping_a_cluster_is_measured_after_the_drop() {
// woman, a dropped bidi control, skin tone: the terminal sees one 2-wide cluster.
let t = CellText::new("\u{1f469}\u{202c}\u{1f3fd}");
assert_eq!(t.as_str(), "\u{1f469}\u{1f3fd}");
assert_eq!(t.clusters().map(|(_, w)| w).collect::<Vec<_>>(), [2]);
// A control turned U+FFFD leaves the mark after it orphaned, and an orphan is dropped.
assert_eq!(CellText::new("\u{1b}\u{301}").as_str(), "\u{fffd}");
}
#[test]
fn tabs_stop_at_eight_from_the_start_of_the_line() {
assert_eq!(CellText::new("\t").as_str(), " ".repeat(8));
assert_eq!(CellText::new("\t\t").as_str(), " ".repeat(16));
assert_eq!(CellText::new("abcdefgh\t").as_str(), format!("abcdefgh{}", " ".repeat(8)));
assert_eq!(CellText::new("abc\t\td").as_str(), format!("abc{}d", " ".repeat(13)));
assert_eq!(CellText::new("\u{4e2d}\tx").as_str(), format!("\u{4e2d}{}x", " ".repeat(6)));
// After a soft break the stop counts from the wrapped line, not the paragraph.
assert_eq!(lines("aaaaaaaa bb\tc", 9), ["aaaaaaaa", "bb c"]);
// A tab is a space: it hangs at a soft break.
assert_eq!(lines("abcdef\tgh", 7), ["abcdef", "gh"]);
assert_eq!(lines("ab cd", 9), ["ab", "cd"]);
assert_eq!(lines("ab cd", 10), ["ab cd"]);
assert_eq!(leaf_measure("a b", true, None, Avail::MinContent).0, 1.0);
assert_eq!(leaf_measure("a b", false, None, Avail::MaxContent).0, 9.0);
}
#[test]
fn width_zero_is_one_cluster_per_line() {
assert_eq!(lines("abc", 0), ["a", "b", "c"]);
assert_eq!(lines("a b", 0), ["a", "b"]);
assert_eq!(lines("\u{4e2d}x", 0), ["\u{4e2d}", "x"]);
assert_eq!(lines(" a", 2), [" ", "a"]);
assert_eq!(layout_lines("abc", true, None, -3.0), ["a", "b", "c"]);
assert_eq!(layout_lines("abc", true, None, f32::NAN), ["a", "b", "c"]);
assert_eq!(leaf_measure("abc", true, None, Avail::Definite(0.0)), (1.0, 3.0));
assert!(lines("abc def", 0).iter().all(|l| !l.is_empty()));
}
#[test]
fn every_scalar_is_clean() {
for c in (0..=char::MAX as u32).filter_map(char::from_u32) {
let t = CellText::new(&c.to_string());
assert!(!t.as_str().chars().any(|c| c.is_control()), "{:#x}", c as u32);
assert!(t.clusters().all(|(_, w)| (1..=3).contains(&w)), "{:#x}", c as u32);
}
}
fn leaf_measure(text: &str, wrap: bool, max_lines: Option<u32>, room: Avail) -> (f32, f32) {
let node = NodeId::new("n");
let content = Bound::Text(text.to_string());
let leaf = Leaf::Text { node: &node, content: &content, style_token: "body", wrap, max_lines };
CellMeasure.measure(&leaf, Constraint { known: [None, None], available: [room, Avail::MaxContent] })
}
fn layout_lines(text: &str, wrap: bool, max_lines: Option<u32>, width: f32) -> Vec<String> {
let node = NodeId::new("n");
let request = TextRequest { node: &node, text, style_token: "body", wrap, max_lines };
CellMeasure
.text(&request, width)
.lines
.into_iter()
.enumerate()
.map(|(row, line)| {
assert_eq!((line.y, line.height), (row as f32, 1.0));
match line.run {
Run::Cells { text, .. } => text.as_str().to_string(),
other => panic!("{other:?}"),
}
})
.collect()
}
fn lines(text: &str, width: u32) -> Vec<String> {
layout_lines(text, true, None, width as f32)
}
#[test]
fn wrap_table() {
assert_eq!(lines("hello world", 5), ["hello", "world"]);
assert_eq!(lines("hello world", 11), ["hello world"]);
let han = "\u{4e2d}\u{6587}\u{6587}\u{5b57}";
assert_eq!(lines(han, 5), ["\u{4e2d}\u{6587}", "\u{6587}\u{5b57}"]);
assert_eq!(lines(han, 3).len(), 4);
assert_eq!(lines("\u{4e2d}", 1), ["\u{4e2d}"]);
assert_eq!(leaf_measure("\u{4e2d}", true, None, Avail::Definite(1.0)), (2.0, 1.0));
assert_eq!(lines("abcdefgh", 3), ["abc", "def", "gh"]);
assert_eq!(layout_lines("a\nb", false, None, 80.0), ["a", "b"]);
assert_eq!(layout_lines("a\r\nb\u{2028}c", true, None, 80.0), ["a", "b", "c"]);
assert_eq!(layout_lines("a\nb", true, Some(1), 80.0), ["a"]);
assert_eq!(lines("hello world", 5), ["hello", "world"]);
assert_eq!(lines("", 5), [""]);
assert_eq!(lines("a\n\nb", 5), ["a", "", "b"]);
assert_eq!(lines("a\n", 5), ["a"]);
// A break opportunity that falls before a dropped mark (LRM here) is kept for the next cluster.
assert_eq!(lines("a \u{200e}bcd", 3), ["a", "bcd"]);
// A cluster never splits, however narrow the room.
assert_eq!(lines("\u{1f468}\u{200d}\u{1f469}", 1), ["\u{1f468}\u{200d}\u{1f469}"]);
assert_eq!(lines("e\u{301}e\u{301}", 1), ["e\u{301}", "e\u{301}"]);
assert_eq!(leaf_measure("hello world", true, None, Avail::MinContent).0, 5.0);
assert_eq!(leaf_measure("a\nbcd", true, None, Avail::MaxContent).0, 3.0);
assert_eq!(leaf_measure("a\nbcd", false, None, Avail::MinContent), (3.0, 2.0));
}
#[test]
fn measure_agrees_with_text() {
let rows: &[(&str, bool, Option<u32>, u32)] = &[
("hello world", true, None, 5),
("hello world", true, None, 11),
("\u{4e2d}\u{6587}\u{6587}\u{5b57}", true, None, 5),
("\u{4e2d}\u{6587}\u{6587}\u{5b57}", true, None, 3),
("\u{4e2d}", true, None, 1),
("abcdefgh", true, None, 3),
("a\nb", false, None, 80),
("a\nb", true, Some(1), 80),
("one two three\tfour five", true, Some(3), 7),
("\u{1f469}\u{200d}\u{1f469} x \u{1f600}\u{1f600}\u{1f600}", true, None, 4),
("", true, None, 4),
];
for &(text, wrap, max_lines, width) in rows {
let laid = layout_lines(text, wrap, max_lines, width as f32);
let (w, h) = leaf_measure(text, wrap, max_lines, Avail::Definite(width as f32));
let widest = laid.iter().map(|l| CellText::new(l).width()).max().unwrap_or(0);
assert_eq!((w, h), (widest as f32, laid.len() as f32), "{text:?} at {width}");
}
}
#[test]
fn controls_have_shipped_sizes() {
let node = NodeId::new("n");
let text = Bound::Text(String::new());
let c = Constraint { known: [None, None], available: [Avail::MaxContent, Avail::MaxContent] };
let mut m = CellMeasure;
assert_eq!(m.measure(&Leaf::TextInput { node: &node, multiline: false, placeholder: &text, value: &text }, c), (25.0, 1.0));
assert_eq!(m.measure(&Leaf::TextInput { node: &node, multiline: true, placeholder: &text, value: &text }, c), (25.0, 3.0));
assert_eq!(m.measure(&Leaf::Toggle { node: &node }, c), (5.0, 1.0));
assert_eq!(m.measure(&Leaf::Slider { node: &node }, c), (20.0, 1.0));
assert_eq!(m.measure(&Leaf::Select { node: &node, selected: &text }, c), (20.0, 1.0));
assert_eq!(m.measure(&Leaf::Image { node: &node, asset: &Bound::Absent }, c), (0.0, 0.0));
let entry = AssetEntry { id: "a".into(), media_type: "image/png".into(), uri: "asset://a".into(), width: count(17), height: count(33) };
assert_eq!(m.measure(&Leaf::Image { node: &node, asset: &Bound::Asset(entry) }, c), (3.0, 3.0), "extent over (8, 16), rounded up");
}
/// Random strings, every control among them, never panic and never put a control character into
/// any line at any width.
#[test]
fn fuzz_never_emits_a_control() {
let mut seed = 0x9e37_79b9_7f4a_7c15_u64;
let mut next = move || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed
};
let pool: Vec<char> = (0u32..0x20)
.chain(0x7f..0xa0)
.chain([0x2028, 0x2029, 0x200b, 0x200d, 0xfe0f, 0x301, 0x20, 0x9, 0x4e2d, 0x1f600, 0x1f469, 0x1f3fd, 0x202c, 0x1f1ef, 0x1f1f5, 0x600, 0x20e3])
.filter_map(char::from_u32)
.collect();
for round in 0..400_000 {
let text: String = if round % 4 == 0 {
// Raw bytes, so truncated and surrogate encodings become U+FFFD.
let bytes: Vec<u8> = (0..(next() % 40)).map(|_| next() as u8).collect();
String::from_utf8_lossy(&bytes).into_owned()
} else {
(0..(next() % 40))
.map(|_| match next() % 3 {
0 => pool[(next() % pool.len() as u64) as usize],
1 => char::from_u32((next() % 0x30000) as u32).unwrap_or('\u{fffd}'),
_ => char::from(b'a' + (next() % 26) as u8),
})
.collect()
};
let width = (next() % 12) as f32;
let wrap = next() % 2 == 0;
for line in layout_lines(&text, wrap, None, width) {
assert!(!line.chars().any(|c| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}')), "{text:?} -> {line:?}");
}
// What is emitted measures to what was recorded: measuring it again changes nothing.
let node = NodeId::new("n");
let request = TextRequest { node: &node, text: &text, style_token: "body", wrap, max_lines: None };
for line in CellMeasure.text(&request, width).lines {
let Run::Cells { text: emitted, .. } = line.run else { panic!() };
assert_eq!(CellText::new(emitted.as_str()), emitted, "{text:?} at {width}");
assert!(emitted.clusters().all(|(_, w)| w >= 1));
}
let lone = CellText::new(&text);
assert_eq!(CellText::new(lone.as_str()), lone, "{text:?}");
let _ = leaf_measure(&text, wrap, Some(3), Avail::Definite(width));
let _ = leaf_measure(&text, wrap, None, Avail::MinContent);
assert!(!CellText::new(&text).as_str().chars().any(|c| c.is_control()));
}
}

View file

@ -0,0 +1,490 @@
//! The frame entry: Core::frame equals the stages composed by hand, and keeps its promises
//! about the port, the last good frame and the room it is given.
use thing_contract::*;
use thing_core::bind::Binder;
use thing_core::diagnostic::Code;
use thing_core::input::{InputEvent, Key, Modifiers, PointerButton, WheelUnit};
use thing_core::layout::{LayoutFrame, Metrics, layout};
use thing_core::port::{Address, Ledger};
use thing_core::render::{RenderCommand, RenderInput, ScrollOffsets, render};
use thing_core::resolve::{Limits, resolve};
use thing_core::theme::Theme;
use thing_core::time::Timestamp;
use thing_core::{Config, Core, FrameInput, FrameOutput, Ports};
use thing_testkit::build::*;
use thing_testkit::fixture::Fixture;
use thing_testkit::measure::FixedMeasure;
use thing_testkit::mem_state::{Call, MemState};
use thing_testkit::state::{self, Swarm};
const PROVIDER: &str = "provider.frame";
fn measure(metrics: Metrics) -> FixedMeasure {
match metrics {
Metrics::Pixels => FixedMeasure::pixels(),
Metrics::Cells => FixedMeasure::cells(),
}
}
fn fresh(metrics: Metrics) -> Core {
Core::new(Config::new(metrics), Box::new(measure(metrics)))
}
fn input(viewport: (f32, f32), scale: f32) -> FrameInput {
FrameInput { now: Timestamp(0), viewport, scale, events: vec![] }
}
fn run(core: &mut Core, state: &mut MemState, input: FrameInput) -> FrameOutput {
core.frame(input, Ports { state })
}
fn show(core: &mut Core, document: &SurfaceDocument) {
core.show(document.provider_id.clone(), RecordKey::new(document.record_key()));
}
fn world(fixture: Fixture) -> MemState {
let mut state = MemState::from_fixture(fixture);
state::script(fixture, &mut state);
state
}
/// The commands of the stages composed by hand, as tests/render.rs composes them.
fn staged(document: &SurfaceDocument, state: &mut MemState, viewport: (f32, f32), scale: f32, metrics: Metrics) -> Vec<RenderCommand> {
let limits = Limits::default();
let tree = resolve(document, state, &limits).tree.expect("resolves");
let mut binder = Binder::new(limits);
binder.bind(tree, state, &mut Ledger::new());
let bound = binder.tree(&document.record_key()).expect("bound");
let frame = LayoutFrame { viewport, scale, metrics };
let laid = layout(bound, &frame, &mut measure(metrics)).unwrap();
let scroll = ScrollOffsets::default();
let theme = Theme::std();
let input = RenderInput { scale, metrics, viewport, scroll: &scroll, theme: &theme };
render(bound, &laid, &input, &mut measure(metrics)).commands
}
fn inline(version: i64, root: Node) -> SurfaceDocument {
SurfaceDocument {
provider_id: ProviderId::new(PROVIDER),
label: seg("main"),
version: ver(version),
title: "frame".into(),
root,
commands: vec![],
}
}
fn say(version: i64, words: &str) -> SurfaceDocument {
inline(version, boxed("root", vec![text("words", words)]))
}
fn surface_address(document: &SurfaceDocument) -> Address {
Address {
provider: document.provider_id.clone(),
schema: SchemaId::new(SurfaceDocument::SCHEMA_NAME),
key: RecordKey::new(document.record_key()),
}
}
fn codes(output: &FrameOutput) -> Vec<Code> {
output.diagnostics.iter().map(|diagnostic| diagnostic.code).collect()
}
fn count(state: &MemState, wanted: impl Fn(&Call) -> bool) -> usize {
state.calls().iter().filter(|call| wanted(call)).count()
}
#[test]
fn pipeline_equals_the_stages() {
let cells = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
let mut state = world(Fixture::F01SwarmDashboard);
let mut one = fresh(Metrics::Cells);
show(&mut one, &cells);
let output = run(&mut one, &mut state, input((100.0, 37.0), 1.0));
let expected = staged(&cells, &mut world(Fixture::F01SwarmDashboard), (100.0, 37.0), 1.0, Metrics::Cells);
assert!(!expected.is_empty());
assert_eq!(output.commands, expected);
assert_eq!(output.next_wake, None);
let list = Fixture::F06ScrollList.load().surfaces.remove(0);
let mut state = world(Fixture::F06ScrollList);
let mut two = fresh(Metrics::Pixels);
show(&mut two, &list);
let output = run(&mut two, &mut state, input((800.0, 600.0), 1.5));
let expected = staged(&list, &mut world(Fixture::F06ScrollList), (800.0, 600.0), 1.5, Metrics::Pixels);
assert!(!expected.is_empty());
assert_eq!(output.commands, expected);
}
#[test]
fn an_idle_frame_draws_the_same_and_drains_once() {
let document = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
let mut state = world(Fixture::F01SwarmDashboard);
let mut core = fresh(Metrics::Cells);
show(&mut core, &document);
let first = run(&mut core, &mut state, input((100.0, 37.0), 1.0));
assert_eq!(count(&state, |call| *call == Call::Drain), 1);
let before = state.calls().len();
let second = run(&mut core, &mut state, input((100.0, 37.0), 1.0));
assert_eq!(second.commands, first.commands);
assert_eq!(state.calls()[before..], [Call::Drain]);
}
#[test]
fn show_holds_the_interest_before_it_reads_and_draws_when_published() {
let document = say(1, "hello");
let mut state = MemState::new();
let mut core = fresh(Metrics::Cells);
show(&mut core, &document);
let output = run(&mut core, &mut state, input((40.0, 5.0), 1.0));
assert_eq!(output.commands, vec![]);
assert_eq!(output.diagnostics, vec![]);
let address = surface_address(&document);
let calls = state.calls();
let subscribe = calls.iter().position(|call| matches!(call, Call::Subscribe(interest) if interest.matches(&address))).expect("subscribed");
let read = calls.iter().position(|call| *call == Call::Read(address.clone())).expect("read");
assert!(subscribe < read, "{calls:?}");
state.put(&document.provider_id, &document);
let output = run(&mut core, &mut state, input((40.0, 5.0), 1.0));
assert_eq!(output.commands, staged(&document, &mut MemState::new(), (40.0, 5.0), 1.0, Metrics::Cells));
assert!(!output.commands.is_empty());
}
#[test]
fn a_republish_replaces_the_picture_and_a_delete_empties_it() {
let v1 = say(1, "first");
let v2 = say(2, "second");
let mut state = MemState::new();
state.put(&v1.provider_id, &v1);
let mut core = fresh(Metrics::Cells);
show(&mut core, &v1);
let at = (40.0, 5.0);
let first = run(&mut core, &mut state, input(at, 1.0));
assert_eq!(first.commands, staged(&v1, &mut MemState::new(), at, 1.0, Metrics::Cells));
state.put(&v2.provider_id, &v2);
let second = run(&mut core, &mut state, input(at, 1.0));
assert_eq!(second.commands, staged(&v2, &mut MemState::new(), at, 1.0, Metrics::Cells));
assert_ne!(second.commands, first.commands);
assert_eq!(codes(&second), vec![]);
// The same record delivered again is not news.
state.put(&v2.provider_id, &v2);
let again = run(&mut core, &mut state, input(at, 1.0));
assert_eq!(codes(&again), vec![]);
assert_eq!(again.commands, second.commands);
// A different document at the held version is refused and the held one stays.
let other = say(2, "impostor");
state.put(&other.provider_id, &other);
let stale = run(&mut core, &mut state, input(at, 1.0));
assert_eq!(codes(&stale), vec![Code::StaleVersionIgnored]);
assert_eq!(stale.commands, second.commands);
state.delete(&surface_address(&v2));
let gone = run(&mut core, &mut state, input(at, 1.0));
assert_eq!(gone.commands, vec![]);
}
#[test]
fn a_changed_state_record_draws_and_a_late_composition_rebinds() {
let document = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
let mut state = world(Fixture::F01SwarmDashboard);
let mut core = fresh(Metrics::Cells);
show(&mut core, &document);
let at = (100.0, 37.0);
let before = run(&mut core, &mut state, input(at, 1.0));
let summary = Swarm { id: "summary".into(), name: "Swarm".into(), load: 0.93 };
state.put_state(&ProviderId::new("provider.swarm"), "summary", &summary);
let after = run(&mut core, &mut state, input(at, 1.0));
let mut moved = world(Fixture::F01SwarmDashboard);
moved.put_state(&ProviderId::new("provider.swarm"), "summary", &summary);
assert_eq!(after.commands, staged(&document, &mut moved, at, 1.0, Metrics::Cells));
assert_ne!(after.commands, before.commands);
// f09: the surface is published first and its composition after.
let stack = Fixture::F09CompositionStack.load();
let surface = stack.surfaces[0].clone();
let mut state = MemState::new();
state.put(&surface.provider_id, &surface);
for (key, record) in state::swarm_records() {
state.put_state(&ProviderId::new("provider.stack"), key, &record);
}
let mut late = fresh(Metrics::Cells);
show(&mut late, &surface);
let placeholder = run(&mut late, &mut state, input(at, 1.0));
assert!(codes(&placeholder).contains(&Code::UnresolvedUse), "{:?}", codes(&placeholder));
for composition in &stack.compositions {
state.put(&ProviderId::new(composition.publisher.clone()), composition);
}
let resolved = run(&mut late, &mut state, input(at, 1.0));
let mut full = MemState::from_fixture(Fixture::F09CompositionStack);
for (key, record) in state::swarm_records() {
full.put_state(&ProviderId::new("provider.stack"), key, &record);
}
assert_eq!(resolved.commands, staged(&surface, &mut full, at, 1.0, Metrics::Cells));
assert_ne!(resolved.commands, placeholder.commands);
}
#[test]
fn no_room_draws_nothing_without_a_diagnostic_and_the_next_frame_draws_again() {
let document = say(1, "room");
let mut state = MemState::new();
state.put(&document.provider_id, &document);
let mut core = fresh(Metrics::Cells);
show(&mut core, &document);
let first = run(&mut core, &mut state, input((40.0, 5.0), 1.0));
assert!(!first.commands.is_empty());
let cramped = run(&mut core, &mut state, input((0.0, 37.0), 1.0));
assert_eq!(cramped.commands, vec![]);
assert_eq!(cramped.diagnostics, vec![]);
let again = run(&mut core, &mut state, input((40.0, 5.0), 1.0));
assert_eq!(again.commands, first.commands);
}
#[test]
fn a_layout_past_the_precision_bound_keeps_the_last_good_frame() {
let good = say(1, "fits");
// Two boxes side by side that together reach past the bound: neither alone is refused.
let slab = |id: &str| match boxed(id, vec![]) {
Node::Box(mut slab) => {
slab.style.size = size2(px(1_500_000.0), px(10.0));
Node::Box(slab)
}
other => other,
};
let mut wide = inline(2, boxed("root", vec![slab("left"), slab("right")]));
if let Node::Box(root) = &mut wide.root {
root.style.direction = Direction::Row;
}
let mut state = MemState::new();
state.put(&good.provider_id, &good);
let mut core = fresh(Metrics::Pixels);
show(&mut core, &good);
let first = run(&mut core, &mut state, input((800.0, 600.0), 1.0));
assert!(!first.commands.is_empty());
state.put(&wide.provider_id, &wide);
let refused = run(&mut core, &mut state, input((800.0, 600.0), 1.0));
assert_eq!(refused.commands, first.commands);
assert_eq!(codes(&refused), vec![Code::LayoutOutOfRange]);
}
fn every_event() -> Vec<InputEvent> {
let modifiers = Modifiers { shift: true, ctrl: false, alt: true, meta: false };
let at = (3.5, 2.5);
vec![
InputEvent::Key { key: Key::Char('A'), modifiers, repeat: false },
InputEvent::Key { key: Key::F(5), modifiers: Modifiers::default(), repeat: true },
InputEvent::Text("hi".into()),
InputEvent::Compose { text: "か".into(), cursor: Some((0, 3)) },
InputEvent::PointerDown { at, button: PointerButton::Primary, modifiers },
InputEvent::PointerMove { at, modifiers },
InputEvent::PointerUp { at, button: PointerButton::Primary, modifiers },
InputEvent::PointerCancel,
InputEvent::Wheel { at, delta: (0.0, 1.0), unit: WheelUnit::Lines, modifiers },
InputEvent::Focus(false),
]
}
#[test]
fn this_cut_routes_no_input_event() {
let document = Fixture::F06ScrollList.load().surfaces.remove(0);
let at = (800.0, 600.0);
let (mut quiet_state, mut busy_state) = (world(Fixture::F06ScrollList), world(Fixture::F06ScrollList));
let (mut quiet, mut busy) = (fresh(Metrics::Pixels), fresh(Metrics::Pixels));
show(&mut quiet, &document);
show(&mut busy, &document);
let plain = run(&mut quiet, &mut quiet_state, input(at, 1.0));
let mut with_events = input(at, 1.0);
with_events.events = every_event();
let output = run(&mut busy, &mut busy_state, with_events);
assert_eq!(output, plain);
assert_eq!(busy_state.calls(), quiet_state.calls());
}
#[test]
fn showing_another_surface_releases_the_first() {
let (a, b) = (say(1, "alpha"), {
let mut b = say(1, "beta");
b.label = seg("other");
b
});
let mut state = MemState::new();
state.put(&a.provider_id, &a);
state.put(&b.provider_id, &b);
let mut core = fresh(Metrics::Cells);
let at = (40.0, 5.0);
show(&mut core, &a);
let first = run(&mut core, &mut state, input(at, 1.0));
assert_eq!(count(&state, |call| matches!(call, Call::Unsubscribe(_))), 0);
show(&mut core, &b);
let second = run(&mut core, &mut state, input(at, 1.0));
assert_eq!(count(&state, |call| matches!(call, Call::Unsubscribe(_))), 1);
assert_eq!(second.commands, staged(&b, &mut MemState::new(), at, 1.0, Metrics::Cells));
assert_ne!(second.commands, first.commands);
}
/// A random box tree: sizes from a hostile list (zero, negative, NaN, past the bound), scroll and
/// clip boxes, texts.
fn random_node(next: &mut dyn FnMut() -> u64, id: &mut u32, depth: u32) -> Node {
let sizes = [0.0, 1.0, 7.5, 40.0, 100.0, 5000.0, 1e6, 1e7, -4.0, f64::NAN];
*id += 1;
let name = format!("n{id}");
if depth == 0 || next() % 4 == 0 {
return text(&name, &format!("text {id}"));
}
let Node::Box(mut node) = boxed(&name, vec![]) else { unreachable!() };
node.style.size = size2(px(sizes[(next() % 10) as usize]), px(sizes[(next() % 10) as usize]));
node.style.direction = if next() % 2 == 0 { Direction::Row } else { Direction::Column };
node.style.overflow = [Overflow::Visible, Overflow::Clip, Overflow::Scroll][(next() % 3) as usize].clone();
let children = next() % 4;
node.children = (0..children).map(|_| random_node(next, id, depth - 1)).collect();
Node::Box(node)
}
/// Fixed seeds for reproducibility, plus `THING_FRAME_SEED` when set; a failure names its seed.
#[test]
fn random_documents_and_inputs_never_panic_and_the_frame_is_deterministic() {
let mut seeds = vec![0x9E37_79B9_7F4A_7C15u64, 0xD1B5_4A32_D192_ED03, 0x2545_F491_4F6C_DD1D, 7];
if let Some(extra) = std::env::var("THING_FRAME_SEED").ok().and_then(|v| v.parse().ok()) {
seeds.push(extra);
}
for seed in seeds {
random_run(seed);
}
}
fn random_run(mut seed: u64) {
let mut next = move || {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
seed
};
let rooms = [(100.0, 37.0), (0.0, 0.0), (-5.0, 10.0), (f32::NAN, 4.0), (f32::INFINITY, 4.0), (800.0, 600.0), (1e9, 1e9), (1.0, 1.0)];
let scales = [1.0, 1.5, 0.0, -1.0, f32::NAN, f32::INFINITY, 1e6, 2.0];
for metrics in [Metrics::Pixels, Metrics::Cells] {
let (mut left, mut right) = (fresh(metrics), fresh(metrics));
let (mut left_state, mut right_state) = (MemState::new(), MemState::new());
let mut shown = false;
for round in 0..200i64 {
if next() % 9 != 0 {
let mut id = 0;
let document = inline(round + 1, random_node(&mut next, &mut id, 4));
if !shown {
show(&mut left, &document);
show(&mut right, &document);
shown = true;
}
left_state.put(&document.provider_id, &document);
right_state.put(&document.provider_id, &document);
} else if shown {
let address = surface_address(&inline(1, boxed("root", vec![])));
left_state.delete(&address);
right_state.delete(&address);
}
let room = rooms[(next() % 8) as usize];
let scale = scales[(next() % 8) as usize];
let events = every_event().into_iter().take((next() % 11) as usize).collect::<Vec<_>>();
let frame = FrameInput { now: Timestamp(round), viewport: room, scale, events };
let one = run(&mut left, &mut left_state, frame.clone());
let two = run(&mut right, &mut right_state, frame);
assert_eq!(one, two, "seed {seed} round {round} in {metrics:?} at {room:?} scale {scale}");
}
}
}
fn wide(version: i64) -> SurfaceDocument {
let slab = |id: &str| match boxed(id, vec![]) {
Node::Box(mut slab) => {
slab.style.size = size2(px(1_500_000.0), px(10.0));
Node::Box(slab)
}
other => other,
};
let mut document = inline(version, boxed("root", vec![slab("left"), slab("right")]));
if let Node::Box(root) = &mut document.root {
root.style.direction = Direction::Row;
}
document
}
#[test]
fn the_last_good_frame_is_cleared_by_a_delete_and_a_switch_and_kept_through_a_frame_error() {
let at = (800.0, 600.0);
let good = say(1, "fits");
// Kept through a room with no size: a refused layout afterwards still shows it.
let mut state = MemState::new();
state.put(&good.provider_id, &good);
let mut one = fresh(Metrics::Pixels);
show(&mut one, &good);
let first = run(&mut one, &mut state, input(at, 1.0));
run(&mut one, &mut state, input((f32::NAN, 600.0), 1.0));
state.put(&good.provider_id, &wide(2));
let held = run(&mut one, &mut state, input(at, 1.0));
assert_eq!(held.commands, first.commands);
assert_eq!(codes(&held), vec![Code::LayoutOutOfRange]);
// Cleared by a delete: what comes after has no frame to fall back on.
let mut state = MemState::new();
state.put(&good.provider_id, &good);
let mut two = fresh(Metrics::Pixels);
show(&mut two, &good);
run(&mut two, &mut state, input(at, 1.0));
state.delete(&surface_address(&good));
assert_eq!(run(&mut two, &mut state, input(at, 1.0)).commands, vec![]);
// The tombstone keeps the version: the same document again, and a different one at it, change nothing shown.
state.put(&good.provider_id, &good);
let replay = run(&mut two, &mut state, input(at, 1.0));
assert_eq!((codes(&replay), replay.commands), (vec![], vec![]));
state.put(&good.provider_id, &say(1, "other"));
let refused = run(&mut two, &mut state, input(at, 1.0));
assert_eq!((codes(&refused), refused.commands), (vec![Code::StaleVersionIgnored], vec![]));
state.put(&good.provider_id, &wide(2));
let out = run(&mut two, &mut state, input(at, 1.0));
assert_eq!((codes(&out), out.commands), (vec![Code::LayoutOutOfRange], vec![]));
// Cleared by a switch.
let other = {
let mut other = wide(1);
other.label = seg("other");
other
};
let mut state = MemState::new();
state.put(&good.provider_id, &good);
state.put(&other.provider_id, &other);
let mut three = fresh(Metrics::Pixels);
show(&mut three, &good);
run(&mut three, &mut state, input(at, 1.0));
show(&mut three, &other);
let switched = run(&mut three, &mut state, input(at, 1.0));
assert_eq!((codes(&switched), switched.commands), (vec![Code::LayoutOutOfRange], vec![]));
}
#[test]
fn a_switch_leaves_the_old_surface_holding_no_interest() {
let swarm = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
let other = say(1, "elsewhere");
let mut state = world(Fixture::F01SwarmDashboard);
state.put(&other.provider_id, &other);
let mut core = fresh(Metrics::Cells);
let at = (100.0, 37.0);
show(&mut core, &swarm);
run(&mut core, &mut state, input(at, 1.0));
let subscribed = count(&state, |call| matches!(call, Call::Subscribe(_)));
assert!(subscribed > 1, "f01 binds provider state, so more than its own record is held");
show(&mut core, &other);
run(&mut core, &mut state, input(at, 1.0));
let subscribes = count(&state, |call| matches!(call, Call::Subscribe(_)));
let unsubscribes = count(&state, |call| matches!(call, Call::Unsubscribe(_)));
assert_eq!(subscribes - unsubscribes, 1, "only the shown surface's own record is held");
// A record the old surface read now changes nothing and costs no read.
let summary = Swarm { id: "summary".into(), name: "Swarm".into(), load: 0.5 };
state.put_state(&ProviderId::new("provider.swarm"), "summary", &summary);
let before = state.calls().len();
run(&mut core, &mut state, input(at, 1.0));
assert_eq!(state.calls()[before..], [Call::Drain]);
}

View file

@ -0,0 +1,6 @@
# 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

@ -0,0 +1,14 @@
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

@ -0,0 +1,11 @@
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

@ -0,0 +1,8 @@
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

@ -0,0 +1,8 @@
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

@ -0,0 +1,8 @@
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

@ -0,0 +1,8 @@
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

@ -0,0 +1,5 @@
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

@ -0,0 +1,5 @@
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

@ -0,0 +1,6 @@
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

@ -0,0 +1,11 @@
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

@ -0,0 +1,11 @@
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

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,5 @@
surface thing:surface:provider.market.plot viewport 800x600 scale 1 pixels
root 0 0 800 470
line 2 2 300 150
bar 2 160 300 150
area 2 318 300 150

View file

@ -0,0 +1,5 @@
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

@ -0,0 +1,5 @@
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

@ -0,0 +1,14 @@
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

@ -0,0 +1,8 @@
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

@ -0,0 +1,85 @@
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

@ -0,0 +1,7 @@
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

@ -0,0 +1,7 @@
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

@ -0,0 +1,9 @@
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
fill 2 20 48 1 r0 #2c2c3eff
stroke 2 20 48 1 r0 w1 #4a4a60ff
text 2 20 #eeeef4ff cells "Restart" bold=false italic=false underline=false

View file

@ -0,0 +1,9 @@
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]
fill 2 50 398 16 r0 #2c2c3eff
stroke 2 50 398 16 r0 w1 #4a4a60ff
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

@ -0,0 +1,6 @@
surface thing:surface:provider.login.login viewport 800x600 scale 1 pixels
stroke 2 2 796 24 r0 w1 #4a4a60ff
text 4 4 #6e6e80ff font0 size16 [117@0,0 115@8,0 101@16,0 114@24,0 110@32,0 97@40,0 109@48,0 101@56,0]
fill 2 34 796 16 r0 #2c2c3eff
stroke 2 34 796 16 r0 w1 #4a4a60ff
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

@ -0,0 +1,3 @@
surface thing:surface:provider.muninn.input-target viewport 800x600 scale 1 pixels
image 82 3.125 636 357.75 "asset://provider.muninn/board.png" "The board the target sits on"
text 282 122 #eeeef4ff font0 size16 [82@0,0 101@8,0 97@16,0 100@24,0 121@32,0]

View file

@ -0,0 +1,9 @@
surface thing:surface:provider.settings.form viewport 800x600 scale 1 pixels
stroke 2 2 796 20 r0 w1 #4a4a60ff
fill 780 4 16 16 r0 #7c9cffff
fill 2 37.5 796 5 r0 #4a4a60ff
fill 778 30 20 20 r0 #7c9cffff
stroke 2 58 796 24 r0 w1 #4a4a60ff
text 4 60 #eeeef4ff font0 size16 [68@0,0 97@8,0 114@16,0 107@24,0]
stroke 2 90 796 24 r0 w1 #4a4a60ff
text 4 92 #eeeef4ff font0 size16 [56@0,0 48@8,0 56@16,0 48@24,0]

View file

@ -0,0 +1,11 @@
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]
fill 2 292 796 16 r0 #2c2c3eff
stroke 2 292 796 16 r0 w1 #4a4a60ff
text 2 292 #eeeef4ff font0 size16 [68@0,0 101@8,0 108@16,0 101@24,0 116@32,0 101@40,0]
fill 2 316 796 16 r0 #2c2c3eff
stroke 2 316 796 16 r0 w1 #4a4a60ff
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

@ -0,0 +1,11 @@
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]
fill 2 292 796 16 r0 #2c2c3eff
stroke 2 292 796 16 r0 w1 #4a4a60ff
text 2 292 #eeeef4ff font0 size16 [68@0,0 101@8,0 108@16,0 101@24,0 116@32,0 101@40,0]
fill 2 316 796 16 r0 #2c2c3eff
stroke 2 316 796 16 r0 w1 #4a4a60ff
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

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,14 @@
surface thing:surface:provider.market.plot viewport 800x600 scale 1 pixels
clip-push 2 2 300 150 r0
polyline w2 #7c9cffff 2,152 77,77 152,114.5 227,2 302,47
clip-pop
clip-push 2 160 300 150 r0
fill 2 253.75 60 56.25 r0 #7c9cffff
fill 62 206.875 60 103.125 r0 #7c9cffff
fill 122 230.3125 60 79.6875 r0 #7c9cffff
fill 182 160 60 150 r0 #7c9cffff
fill 242 188.125 60 121.875 r0 #7c9cffff
clip-pop
clip-push 2 318 300 150 r0
polygon #7c9cffff 2,168 5.030303,-19.5 8.060606,74.25 11.090909,-207 14.121212,-94.5 14.121212,393 2,393
clip-pop

View file

@ -0,0 +1,4 @@
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

@ -0,0 +1,12 @@
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]
fill 4 72 792 16 r0 #2c2c3eff
stroke 4 72 792 16 r0 w1 #4a4a60ff
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]
fill 6 122 788 16 r0 #2c2c3eff
stroke 6 122 788 16 r0 w1 #4a4a60ff
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

@ -0,0 +1,7 @@
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

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

View file

@ -0,0 +1,31 @@
surface thing:surface:provider.text.text-edge viewport 40x60 scale 1 cells
text 2 2 #eeeef4ff cells "Hello שלום עולם and مرحبا بالعالم" bold=false italic=false underline=false
text 2 3 #eeeef4ff cells "then 123 end." bold=false italic=false underline=false
text 2 12 #eeeef4ff cells "日本語テスト 你好世界 한국어 ABC" bold=false italic=false underline=false widths=2,2,2,2,2,2,1,2,2,2,2,1,2,2,2,1,2,2,2
text 2 13 #eeeef4ff cells "123" bold=false italic=false underline=false widths=2,2,2
text 2 22 #eeeef4ff cells "e\u{301} a\u{308} n\u{303} o\u{302}\u{323} z\u{35b}\u{34f}\u{300}" bold=false italic=false underline=false
text 2 31 #eeeef4ff cells "👩\u{200d}👩\u{200d}👧\u{200d}👦 👨🏽\u{200d}💻 🏳\u{fe0f}\u{200d}🌈" bold=false italic=false underline=false widths=2,1,2,1,2
text 2 40 #eeeef4ff cells "The quick brown fox jumps over the" bold=false italic=false underline=false
text 2 41 #eeeef4ff cells "lazy dog while the evening light" bold=false italic=false underline=false
text 2 42 #eeeef4ff cells "slides across the valley, and the" bold=false italic=false underline=false
text 2 43 #eeeef4ff cells "long paragraph keeps going so that" bold=false italic=false underline=false
text 2 44 #eeeef4ff cells "any reasonable column must break it" bold=false italic=false underline=false
text 2 45 #eeeef4ff cells "across several lines. The quick" bold=false italic=false underline=false
text 2 46 #eeeef4ff cells "brown fox jumps over the lazy dog" bold=false italic=false underline=false
text 2 47 #eeeef4ff cells "while the evening light slides" bold=false italic=false underline=false
text 2 48 #eeeef4ff cells "across the valley, and the long" bold=false italic=false underline=false
text 2 49 #eeeef4ff cells "paragraph keeps going so that any" bold=false italic=false underline=false
text 2 50 #eeeef4ff cells "reasonable column must break it" bold=false italic=false underline=false
text 2 51 #eeeef4ff cells "across several lines. The quick" bold=false italic=false underline=false
text 2 52 #eeeef4ff cells "brown fox jumps over the lazy dog" bold=false italic=false underline=false
text 2 53 #eeeef4ff cells "while the evening light slides" bold=false italic=false underline=false
text 2 54 #eeeef4ff cells "across the valley, and the long" bold=false italic=false underline=false
text 2 55 #eeeef4ff cells "paragraph keeps going so that any" bold=false italic=false underline=false
text 2 56 #eeeef4ff cells "reasonable column must break it" bold=false italic=false underline=false
text 2 57 #eeeef4ff cells "across several lines. The quick" bold=false italic=false underline=false
text 2 58 #eeeef4ff cells "brown fox jumps over the lazy dog" bold=false italic=false underline=false
text 2 59 #eeeef4ff cells "while the evening light slides" bold=false italic=false underline=false
text 2 60 #eeeef4ff cells "across the valley, and the long" bold=false italic=false underline=false
text 2 61 #eeeef4ff cells "paragraph keeps going so that any" bold=false italic=false underline=false
text 2 62 #eeeef4ff cells "reasonable column must break it" bold=false italic=false underline=false
text 2 63 #eeeef4ff cells "across several lines. " bold=false italic=false underline=false

View file

@ -0,0 +1,13 @@
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

@ -0,0 +1,864 @@
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,
},
],
}

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