Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
672c0c1e9f | ||
|
|
436b513431 | ||
|
|
29b0d7741d | ||
|
|
19c3dcf917 | ||
|
|
e5a81185bb | ||
|
|
3a5e2057e0 | ||
|
|
af05248af5 |
278 changed files with 1122 additions and 41704 deletions
35
.github/workflows/portable-contracts.yml
vendored
35
.github/workflows/portable-contracts.yml
vendored
|
|
@ -8,11 +8,6 @@ on:
|
||||||
pull_request:
|
pull_request:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
concurrency:
|
|
||||||
# A newer push or PR update replaces the older run on the same ref; workflow_dispatch runs are never cancelled.
|
|
||||||
group: ${{ github.workflow }}-${{ github.ref }}
|
|
||||||
cancel-in-progress: ${{ github.event_name != 'workflow_dispatch' }}
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
contracts-and-browser:
|
contracts-and-browser:
|
||||||
name: ${{ matrix.os }} ${{ matrix.package }}
|
name: ${{ matrix.os }} ${{ matrix.package }}
|
||||||
|
|
@ -21,10 +16,7 @@ jobs:
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
# No Windows runner exists: the windows-latest leg runs on workflow_dispatch only (GitHub or a
|
os: [windows-latest, ubuntu-latest]
|
||||||
# Windows runner), the ubuntu-latest leg gates push and PR. Windows push/PR triggers return in the PR
|
|
||||||
# that registers a Windows runner.
|
|
||||||
os: ${{ fromJSON(github.event_name == 'workflow_dispatch' && '["windows-latest", "ubuntu-latest"]' || '["ubuntu-latest"]') }}
|
|
||||||
package: [eve-contracts, eve-browser-lowering]
|
package: [eve-contracts, eve-browser-lowering]
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
|
|
@ -38,14 +30,6 @@ jobs:
|
||||||
cache: npm
|
cache: npm
|
||||||
cache-dependency-path: packages/${{ matrix.package }}/package-lock.json
|
cache-dependency-path: packages/${{ matrix.package }}/package-lock.json
|
||||||
|
|
||||||
# eve-browser-lowering links eve-contracts as file:../eve-contracts; npm installs none of the
|
|
||||||
# linked package's dependencies, and tsc resolves its declarations from the real path, so
|
|
||||||
# ajv must be installed in eve-contracts itself.
|
|
||||||
- name: Install eve-contracts dependencies
|
|
||||||
if: matrix.package != 'eve-contracts'
|
|
||||||
working-directory: packages/eve-contracts
|
|
||||||
run: npm ci
|
|
||||||
|
|
||||||
- name: Install package dependencies
|
- name: Install package dependencies
|
||||||
working-directory: packages/${{ matrix.package }}
|
working-directory: packages/${{ matrix.package }}
|
||||||
run: npm ci
|
run: npm ci
|
||||||
|
|
@ -54,23 +38,6 @@ jobs:
|
||||||
working-directory: packages/${{ matrix.package }}
|
working-directory: packages/${{ matrix.package }}
|
||||||
run: npm test
|
run: npm test
|
||||||
|
|
||||||
# The forge runner images carry no pwsh; GitHub's Windows and hosted images do.
|
|
||||||
- name: Install PowerShell
|
|
||||||
if: runner.os == 'Linux'
|
|
||||||
shell: bash
|
|
||||||
run: |
|
|
||||||
set -euo pipefail
|
|
||||||
if command -v pwsh >/dev/null; then pwsh -Version; exit 0; fi
|
|
||||||
SUDO=""; [ "$(id -u)" -eq 0 ] || SUDO="sudo"
|
|
||||||
PWSH_VERSION=7.4.6
|
|
||||||
curl -fsSL "https://github.com/PowerShell/PowerShell/releases/download/v${PWSH_VERSION}/powershell-${PWSH_VERSION}-linux-x64.tar.gz" -o "${RUNNER_TEMP:-/tmp}/powershell.tar.gz"
|
|
||||||
$SUDO mkdir -p /opt/microsoft/powershell/7
|
|
||||||
$SUDO tar -xzf "${RUNNER_TEMP:-/tmp}/powershell.tar.gz" -C /opt/microsoft/powershell/7
|
|
||||||
$SUDO chmod +x /opt/microsoft/powershell/7/pwsh
|
|
||||||
$SUDO ln -sf /opt/microsoft/powershell/7/pwsh /usr/local/bin/pwsh
|
|
||||||
echo "DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1" >> "$GITHUB_ENV"
|
|
||||||
DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 pwsh -Version
|
|
||||||
|
|
||||||
- name: Reject stale generated output
|
- name: Reject stale generated output
|
||||||
shell: pwsh
|
shell: pwsh
|
||||||
run: |
|
run: |
|
||||||
|
|
|
||||||
11
.gitignore
vendored
11
.gitignore
vendored
|
|
@ -8,19 +8,12 @@ packages/eve-browser-lowering/node_modules/
|
||||||
!packages/eve-contracts/**
|
!packages/eve-contracts/**
|
||||||
packages/eve-contracts/node_modules/
|
packages/eve-contracts/node_modules/
|
||||||
packages/eve-contracts/*.tgz
|
packages/eve-contracts/*.tgz
|
||||||
!packages/thing-contract/
|
|
||||||
!packages/thing-contract/**
|
|
||||||
packages/thing-contract/node_modules/
|
|
||||||
packages/thing-contract/dist/
|
|
||||||
packages/thing-contract/dist-test/
|
|
||||||
!packages/org.gamecult.eve.surface/
|
!packages/org.gamecult.eve.surface/
|
||||||
!packages/org.gamecult.eve.surface/**
|
!packages/org.gamecult.eve.surface/**
|
||||||
packages/org.gamecult.eve.surface/bin~/
|
packages/org.gamecult.eve.surface/bin~/
|
||||||
packages/org.gamecult.eve.surface/obj~/
|
packages/org.gamecult.eve.surface/obj~/
|
||||||
!packages/org.gamecult.eve.unity-uitoolkit/
|
!packages/org.gamecult.eve.unity-uitoolkit/
|
||||||
!packages/org.gamecult.eve.unity-uitoolkit/**
|
!packages/org.gamecult.eve.unity-uitoolkit/**
|
||||||
!packages/GameCult.Thing.Contract/
|
|
||||||
!packages/GameCult.Thing.Contract/**
|
|
||||||
obj/
|
obj/
|
||||||
artifacts/
|
artifacts/
|
||||||
tools/deps/
|
tools/deps/
|
||||||
|
|
@ -32,4 +25,6 @@ flutter/eve_parity/assets/repixelizer/
|
||||||
*.deb
|
*.deb
|
||||||
*.ipa
|
*.ipa
|
||||||
*.dSYM/
|
*.dSYM/
|
||||||
/target
|
.voidbot/birth/
|
||||||
|
.voidbot/logs/
|
||||||
|
.voidbot/state/*.msgpack
|
||||||
|
|
|
||||||
8
.voidbot/state/README.md
Normal file
8
.voidbot/state/README.md
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
# Repo Persona State
|
||||||
|
|
||||||
|
This folder stores birth and continuity state for `Eve`.
|
||||||
|
Do not treat these files as arbitrary editable projections. Persistent memory should cross typed operation boundaries.
|
||||||
|
|
||||||
|
`docs/eve-face.md` is the human-readable mission/memory surface for Eve's repo
|
||||||
|
Persona. Keep `.voidbot/state/eve.cc` as the typed authority, and keep the docs
|
||||||
|
surface aligned when Eve's durable mission changes.
|
||||||
BIN
.voidbot/state/eve.cc
Normal file
BIN
.voidbot/state/eve.cc
Normal file
Binary file not shown.
7
.voidbot/status/void-memory-maintenance.json
Normal file
7
.voidbot/status/void-memory-maintenance.json
Normal file
|
|
@ -0,0 +1,7 @@
|
||||||
|
{
|
||||||
|
"status": "starting",
|
||||||
|
"startedAt": "2026-07-08T06:38:39.965Z",
|
||||||
|
"stateFile": "E:\\Projects\\Eve\\.voidbot\\state\\eve.cc",
|
||||||
|
"launcher": "repo_face_heartbeat",
|
||||||
|
"reason": "repo_face_napping_with_short_term_memory"
|
||||||
|
}
|
||||||
4
.voidbot/voice/README.md
Normal file
4
.voidbot/voice/README.md
Normal file
|
|
@ -0,0 +1,4 @@
|
||||||
|
# Repo Persona Voice
|
||||||
|
|
||||||
|
This folder belongs to the Discord-facing Persona for `Eve`.
|
||||||
|
Discord roles address the Persona; VoidBot's webhook persona pipe is the mouth.
|
||||||
BIN
.voidbot/voice/eve.png
Normal file
BIN
.voidbot/voice/eve.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 5.1 KiB |
10
.voidbot/voice/identity.json
Normal file
10
.voidbot/voice/identity.json
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
{
|
||||||
|
"schemaVersion": "voidbot.repo_face_identity.v0",
|
||||||
|
"identityId": "eve",
|
||||||
|
"repoName": "Eve",
|
||||||
|
"displayName": "Eve",
|
||||||
|
"roleId": "1510848465243082874",
|
||||||
|
"avatarUrl": "https://raw.githubusercontent.com/GameCult/VoidBot/codex/voidbot-cultcache-replace-retry/assets/repo-faces/eve.png",
|
||||||
|
"repoPath": "E:\\Projects\\Eve",
|
||||||
|
"createdOrRefreshedAt": "2026-07-08T03:32:39.737Z"
|
||||||
|
}
|
||||||
826
Cargo.lock
generated
826
Cargo.lock
generated
|
|
@ -1,826 +0,0 @@
|
||||||
# This file is automatically @generated by Cargo.
|
|
||||||
# It is not intended for manual editing.
|
|
||||||
version = 4
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "android_system_properties"
|
|
||||||
version = "0.1.6"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
|
|
||||||
dependencies = [
|
|
||||||
"libc",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "anyhow"
|
|
||||||
version = "1.0.104"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
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]]
|
|
||||||
name = "autocfg"
|
|
||||||
version = "1.5.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
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]]
|
|
||||||
name = "bumpalo"
|
|
||||||
version = "3.20.3"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "cc"
|
|
||||||
version = "1.8.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "6651c9ed80effdc7db0ff72512157f901af5e3549e341e24b1dd4887d836d838"
|
|
||||||
dependencies = [
|
|
||||||
"find-msvc-tools",
|
|
||||||
"shlex",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "cfg-if"
|
|
||||||
version = "1.0.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "chrono"
|
|
||||||
version = "0.4.45"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
|
|
||||||
dependencies = [
|
|
||||||
"iana-time-zone",
|
|
||||||
"js-sys",
|
|
||||||
"num-traits",
|
|
||||||
"serde",
|
|
||||||
"wasm-bindgen",
|
|
||||||
"windows-link",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "core-foundation-sys"
|
|
||||||
version = "0.8.7"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
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]]
|
|
||||||
name = "cultcache-rs"
|
|
||||||
version = "0.3.1"
|
|
||||||
source = "git+https://github.com/GameCult/CultLib.git?rev=4c9af401ae33812d862dde4ff3131433fc73c7dc#4c9af401ae33812d862dde4ff3131433fc73c7dc"
|
|
||||||
dependencies = [
|
|
||||||
"anyhow",
|
|
||||||
"chrono",
|
|
||||||
"cultcache-rs-derive",
|
|
||||||
"fs2",
|
|
||||||
"redb",
|
|
||||||
"rmp-serde",
|
|
||||||
"serde",
|
|
||||||
"serde_bytes",
|
|
||||||
"serde_json",
|
|
||||||
"serde_stacker",
|
|
||||||
"sha2",
|
|
||||||
"stacker",
|
|
||||||
"uuid",
|
|
||||||
"windows-sys 0.59.0",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "cultcache-rs-derive"
|
|
||||||
version = "0.2.0"
|
|
||||||
source = "git+https://github.com/GameCult/CultLib.git?rev=4c9af401ae33812d862dde4ff3131433fc73c7dc#4c9af401ae33812d862dde4ff3131433fc73c7dc"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"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]]
|
|
||||||
name = "find-msvc-tools"
|
|
||||||
version = "0.1.14"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "fs2"
|
|
||||||
version = "0.4.3"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "9564fc758e15025b46aa6643b1b77d047d1a56a1aea6e01002ac0c7026876213"
|
|
||||||
dependencies = [
|
|
||||||
"libc",
|
|
||||||
"winapi",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "futures-core"
|
|
||||||
version = "0.3.34"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "futures-task"
|
|
||||||
version = "0.3.34"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "futures-util"
|
|
||||||
version = "0.3.34"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
|
|
||||||
dependencies = [
|
|
||||||
"futures-core",
|
|
||||||
"futures-task",
|
|
||||||
"pin-project-lite",
|
|
||||||
"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]]
|
|
||||||
name = "getrandom"
|
|
||||||
version = "0.4.3"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
|
|
||||||
dependencies = [
|
|
||||||
"cfg-if",
|
|
||||||
"libc",
|
|
||||||
"r-efi",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "iana-time-zone"
|
|
||||||
version = "0.1.65"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
|
|
||||||
dependencies = [
|
|
||||||
"android_system_properties",
|
|
||||||
"core-foundation-sys",
|
|
||||||
"iana-time-zone-haiku",
|
|
||||||
"js-sys",
|
|
||||||
"log",
|
|
||||||
"wasm-bindgen",
|
|
||||||
"windows-core",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "iana-time-zone-haiku"
|
|
||||||
version = "0.1.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
|
|
||||||
dependencies = [
|
|
||||||
"cc",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "itoa"
|
|
||||||
version = "1.0.18"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "js-sys"
|
|
||||||
version = "0.3.106"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5"
|
|
||||||
dependencies = [
|
|
||||||
"cfg-if",
|
|
||||||
"futures-util",
|
|
||||||
"wasm-bindgen",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "libc"
|
|
||||||
version = "0.2.190"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "log"
|
|
||||||
version = "0.4.34"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "memchr"
|
|
||||||
version = "2.8.3"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "num-traits"
|
|
||||||
version = "0.2.19"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
|
||||||
dependencies = [
|
|
||||||
"autocfg",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "object"
|
|
||||||
version = "0.39.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b"
|
|
||||||
dependencies = [
|
|
||||||
"memchr",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "once_cell"
|
|
||||||
version = "1.21.4"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "pin-project-lite"
|
|
||||||
version = "0.2.17"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "proc-macro2"
|
|
||||||
version = "1.0.107"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
|
||||||
dependencies = [
|
|
||||||
"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]]
|
|
||||||
name = "quote"
|
|
||||||
version = "1.0.47"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "r-efi"
|
|
||||||
version = "6.0.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "redb"
|
|
||||||
version = "4.3.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "fb338a6c67830a61bed824b78c2bb034ab1ff401a20616bd7957524f4fdc2f22"
|
|
||||||
dependencies = [
|
|
||||||
"libc",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "rmp"
|
|
||||||
version = "0.8.15"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "4ba8be72d372b2c9b35542551678538b562e7cf86c3315773cae48dfbfe7790c"
|
|
||||||
dependencies = [
|
|
||||||
"num-traits",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "rmp-serde"
|
|
||||||
version = "1.3.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "72f81bee8c8ef9b577d1681a70ebbc962c232461e397b22c208c43c04b67a155"
|
|
||||||
dependencies = [
|
|
||||||
"rmp",
|
|
||||||
"serde",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "rustc-hash"
|
|
||||||
version = "2.1.3"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "rustversion"
|
|
||||||
version = "1.0.23"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "serde"
|
|
||||||
version = "1.0.229"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
|
||||||
dependencies = [
|
|
||||||
"serde_core",
|
|
||||||
"serde_derive",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "serde_bytes"
|
|
||||||
version = "0.11.19"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "a5d440709e79d88e51ac01c4b72fc6cb7314017bb7da9eeff678aa94c10e3ea8"
|
|
||||||
dependencies = [
|
|
||||||
"serde",
|
|
||||||
"serde_core",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "serde_core"
|
|
||||||
version = "1.0.229"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
|
||||||
dependencies = [
|
|
||||||
"serde_derive",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "serde_derive"
|
|
||||||
version = "1.0.229"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn 3.0.8",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "serde_json"
|
|
||||||
version = "1.0.154"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
|
||||||
dependencies = [
|
|
||||||
"itoa",
|
|
||||||
"memchr",
|
|
||||||
"serde",
|
|
||||||
"serde_core",
|
|
||||||
"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]]
|
|
||||||
name = "shlex"
|
|
||||||
version = "2.0.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "slab"
|
|
||||||
version = "0.4.12"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
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]]
|
|
||||||
name = "syn"
|
|
||||||
version = "2.0.119"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"unicode-ident",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "syn"
|
|
||||||
version = "3.0.8"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "01016da373cd8f7ef12624f796309f5c31ba8d646dd08856c02cd741d823c622"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"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]]
|
|
||||||
name = "thing-contract"
|
|
||||||
version = "0.1.0"
|
|
||||||
dependencies = [
|
|
||||||
"anyhow",
|
|
||||||
"cultcache-rs",
|
|
||||||
"rmp-serde",
|
|
||||||
"serde",
|
|
||||||
"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]]
|
|
||||||
name = "unicode-ident"
|
|
||||||
version = "1.0.26"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
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]]
|
|
||||||
name = "uuid"
|
|
||||||
version = "1.28.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "7cc1186384beb7dd8eedea376413fd654937285ea6c9cfbb928dc3043ea4b606"
|
|
||||||
dependencies = [
|
|
||||||
"getrandom",
|
|
||||||
"js-sys",
|
|
||||||
"wasm-bindgen",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "version_check"
|
|
||||||
version = "0.9.5"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "wasm-bindgen"
|
|
||||||
version = "0.2.129"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409"
|
|
||||||
dependencies = [
|
|
||||||
"cfg-if",
|
|
||||||
"once_cell",
|
|
||||||
"rustversion",
|
|
||||||
"wasm-bindgen-macro",
|
|
||||||
"wasm-bindgen-shared",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "wasm-bindgen-macro"
|
|
||||||
version = "0.2.129"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535"
|
|
||||||
dependencies = [
|
|
||||||
"quote",
|
|
||||||
"wasm-bindgen-macro-support",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "wasm-bindgen-macro-support"
|
|
||||||
version = "0.2.129"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7"
|
|
||||||
dependencies = [
|
|
||||||
"bumpalo",
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn 3.0.8",
|
|
||||||
"wasm-bindgen-shared",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "wasm-bindgen-shared"
|
|
||||||
version = "0.2.129"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6"
|
|
||||||
dependencies = [
|
|
||||||
"unicode-ident",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "winapi"
|
|
||||||
version = "0.3.9"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
|
|
||||||
dependencies = [
|
|
||||||
"winapi-i686-pc-windows-gnu",
|
|
||||||
"winapi-x86_64-pc-windows-gnu",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "winapi-i686-pc-windows-gnu"
|
|
||||||
version = "0.4.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "winapi-x86_64-pc-windows-gnu"
|
|
||||||
version = "0.4.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows-core"
|
|
||||||
version = "0.62.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
|
|
||||||
dependencies = [
|
|
||||||
"windows-implement",
|
|
||||||
"windows-interface",
|
|
||||||
"windows-link",
|
|
||||||
"windows-result",
|
|
||||||
"windows-strings",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows-implement"
|
|
||||||
version = "0.60.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn 2.0.119",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows-interface"
|
|
||||||
version = "0.59.3"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn 2.0.119",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows-link"
|
|
||||||
version = "0.2.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows-result"
|
|
||||||
version = "0.4.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
|
|
||||||
dependencies = [
|
|
||||||
"windows-link",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows-strings"
|
|
||||||
version = "0.5.1"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
|
|
||||||
dependencies = [
|
|
||||||
"windows-link",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows-sys"
|
|
||||||
version = "0.59.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b"
|
|
||||||
dependencies = [
|
|
||||||
"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]]
|
|
||||||
name = "windows-targets"
|
|
||||||
version = "0.52.6"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
|
|
||||||
dependencies = [
|
|
||||||
"windows_aarch64_gnullvm",
|
|
||||||
"windows_aarch64_msvc",
|
|
||||||
"windows_i686_gnu",
|
|
||||||
"windows_i686_gnullvm",
|
|
||||||
"windows_i686_msvc",
|
|
||||||
"windows_x86_64_gnu",
|
|
||||||
"windows_x86_64_gnullvm",
|
|
||||||
"windows_x86_64_msvc",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_aarch64_gnullvm"
|
|
||||||
version = "0.52.6"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_aarch64_msvc"
|
|
||||||
version = "0.52.6"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_i686_gnu"
|
|
||||||
version = "0.52.6"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_i686_gnullvm"
|
|
||||||
version = "0.52.6"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_i686_msvc"
|
|
||||||
version = "0.52.6"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_x86_64_gnu"
|
|
||||||
version = "0.52.6"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_x86_64_gnullvm"
|
|
||||||
version = "0.52.6"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "windows_x86_64_msvc"
|
|
||||||
version = "0.52.6"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "zmij"
|
|
||||||
version = "1.0.23"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
|
||||||
15
Cargo.toml
15
Cargo.toml
|
|
@ -1,15 +0,0 @@
|
||||||
[workspace]
|
|
||||||
members = ["crates/*"]
|
|
||||||
resolver = "2"
|
|
||||||
|
|
||||||
[workspace.dependencies]
|
|
||||||
anyhow = "1"
|
|
||||||
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "4c9af401ae33812d862dde4ff3131433fc73c7dc", package = "cultcache-rs" }
|
|
||||||
serde = { version = "1", features = ["derive"] }
|
|
||||||
rmp-serde = "1.3"
|
|
||||||
taffy = { version = "0.16", default-features = false, features = ["std", "taffy_tree", "flexbox", "grid", "block_layout", "content_size"] }
|
|
||||||
# The terminal text tables, pinned exactly: a width is a golden. unicode-width drops its cjk
|
|
||||||
# tables, so ambiguous width is narrow.
|
|
||||||
unicode-width = { version = "=0.2.3", default-features = false }
|
|
||||||
unicode-segmentation = "=1.13.3"
|
|
||||||
unicode-linebreak = "=0.1.5"
|
|
||||||
21
LICENSE
21
LICENSE
|
|
@ -1,21 +0,0 @@
|
||||||
MIT License
|
|
||||||
|
|
||||||
Copyright (c) 2026 GameCult
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
of this software and associated documentation files (the "Software"), to deal
|
|
||||||
in the Software without restriction, including without limitation the rights
|
|
||||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
copies of the Software, and to permit persons to whom the Software is
|
|
||||||
furnished to do so, subject to the following conditions:
|
|
||||||
|
|
||||||
The above copyright notice and this permission notice shall be included in all
|
|
||||||
copies or substantial portions of the Software.
|
|
||||||
|
|
||||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
SOFTWARE.
|
|
||||||
2
Makefile
2
Makefile
|
|
@ -11,7 +11,7 @@ EveCanvas_FILES = \
|
||||||
Sources/EVEViewController.mm \
|
Sources/EVEViewController.mm \
|
||||||
Sources/EVEGLView.mm \
|
Sources/EVEGLView.mm \
|
||||||
Sources/EVEFrameStreamClient.m \
|
Sources/EVEFrameStreamClient.m \
|
||||||
Sources/EVEDashboardClient.m \
|
Sources/EVEHermodrClient.m \
|
||||||
Sources/EVESensorUplinkClient.m \
|
Sources/EVESensorUplinkClient.m \
|
||||||
Sources/EVEH264StreamDecoder.m
|
Sources/EVEH264StreamDecoder.m
|
||||||
|
|
||||||
|
|
|
||||||
111
README.md
111
README.md
|
|
@ -1,41 +1,4 @@
|
||||||
# Thing
|
# Eve
|
||||||
|
|
||||||
This repository is Thing (the Eve display, control and sensor edge for GameCult
|
|
||||||
apps). Its present tree is Thing 1, kept running for live consumers until each
|
|
||||||
ports; Thing 2.0 is built here (`docs/thing2-target.md`). The Thing 1 renderer
|
|
||||||
repos are archived under their Eve names: EveUnity, EveFlutter, EveElectron,
|
|
||||||
EveTui, EvePlugins and EveConformance.
|
|
||||||
|
|
||||||
## Start Here
|
|
||||||
|
|
||||||
Value: services publish a surface once, as a typed retained document
|
|
||||||
(`gamecult.eve.surface.v1`), and every runtime lowers it locally. Providers keep
|
|
||||||
authority over state and commands; Eve owns projection, input capture and
|
|
||||||
timestamped sensor publication.
|
|
||||||
|
|
||||||
Problem: without a shared surface contract, each service hand-builds its own
|
|
||||||
dashboard and each renderer re-implements layout, binding and commands.
|
|
||||||
|
|
||||||
Live (Thing 1):
|
|
||||||
|
|
||||||
- `packages/org.gamecult.eve.surface`: renderer-neutral C# surface contract and
|
|
||||||
composition builders; tests in `tests/GameCult.Eve.Surface.Serialization.Tests`.
|
|
||||||
- `packages/eve-contracts`: TypeScript types and validators generated from
|
|
||||||
`schemas/` (`npm run generate`, `npm test`).
|
|
||||||
- `packages/eve-browser-lowering`: browser DOM/CSS lowering of surface documents
|
|
||||||
(`npm test`).
|
|
||||||
- `web/`: browser reference oracle (`web/index.html`, `web/eve-dsl.js`; tests
|
|
||||||
with `node --test web/eve-dsl.test.mjs`).
|
|
||||||
- `docs/surface-contract-v1.md`: the contract. `docs/repo-strategy.md`: repo
|
|
||||||
ownership. `docs/parity-testing-harness.md` with
|
|
||||||
`scripts/run-parity-harness.ps1`: parity runs.
|
|
||||||
- `android/` and `Sources/` (iOS Theos app, `make package`): native proof
|
|
||||||
clients; build steps under Build Shape below.
|
|
||||||
|
|
||||||
Planned (Thing 2.0, in progress): `crates/thing-contract` is the first Rust
|
|
||||||
piece. The layout solver, text, accessibility tree, closed render-command list
|
|
||||||
and thin backends described in `docs/thing2-target.md` and `docs/thing2-map.md`
|
|
||||||
are not built yet; `docs/thing-campaign.md` holds the rename plan.
|
|
||||||
|
|
||||||
CultMesh-based surface web, portable control layer, and timestamped sensor
|
CultMesh-based surface web, portable control layer, and timestamped sensor
|
||||||
edge.
|
edge.
|
||||||
|
|
@ -139,8 +102,10 @@ schema or composition builders.
|
||||||
|
|
||||||
## Current Mechanism
|
## Current Mechanism
|
||||||
|
|
||||||
The current checked-in client is the iOS Theos app, still named `EveCanvas` at
|
The current checked-in iOS runtime is the Theos app still named `EveCanvas` at
|
||||||
the bundle level until the wider Eve runtime split exists.
|
the bundle level. Its primary input is Gjallar's aggregate surface through the
|
||||||
|
temporary Starfire Hermodr HTTP boundary; direct typed CultMesh transport can
|
||||||
|
replace that edge later without moving layout authority into the client.
|
||||||
|
|
||||||
The Android proof under `android/` is a small native Kotlin client built with
|
The Android proof under `android/` is a small native Kotlin client built with
|
||||||
the installed Android SDK and CultLib's `cultmesh-kotlin` package, without
|
the installed Android SDK and CultLib's `cultmesh-kotlin` package, without
|
||||||
|
|
@ -152,9 +117,12 @@ payloads as `mimir.eve_media_observation.v1`.
|
||||||
|
|
||||||
- `EVEAppDelegate` creates one fullscreen `UIWindow`.
|
- `EVEAppDelegate` creates one fullscreen `UIWindow`.
|
||||||
- `EVEViewController` installs:
|
- `EVEViewController` installs:
|
||||||
|
- `EVEHermodrClient`, the configured live `gjallar.overview` surface client.
|
||||||
|
- native UIKit lowering for generic Eve trees and Gjallar's
|
||||||
|
`weighted-bisect` aggregate.
|
||||||
- `EVEGLView`, a `CAEAGLLayer` backed OpenGL ES render target.
|
- `EVEGLView`, a `CAEAGLLayer` backed OpenGL ES render target.
|
||||||
- a full-screen `UIImageView` that displays CEF relay frames.
|
- an optional full-screen `UIImageView` and `EVEFrameStreamClient` for legacy
|
||||||
- `EVEFrameStreamClient`, a native WebSocket client for frame/input transport.
|
configured frame streams.
|
||||||
- a native UIKit `UILabel` overlay for crisp Retina status text.
|
- a native UIKit `UILabel` overlay for crisp Retina status text.
|
||||||
- `CADisplayLink` for frame ticking.
|
- `CADisplayLink` for frame ticking.
|
||||||
- `CMMotionManager` for accelerometer and gyro telemetry.
|
- `CMMotionManager` for accelerometer and gyro telemetry.
|
||||||
|
|
@ -163,8 +131,10 @@ payloads as `mimir.eve_media_observation.v1`.
|
||||||
- `EVESensorUplinkClient` opens separate WebSocket uplinks for camera and
|
- `EVESensorUplinkClient` opens separate WebSocket uplinks for camera and
|
||||||
microphone observations so sensor traffic does not block display/control
|
microphone observations so sensor traffic does not block display/control
|
||||||
traffic.
|
traffic.
|
||||||
- `EVEDashboardClient` opens the native Mimir dashboard socket and receives
|
- `EVEHermodrClient` polls Odin-owned Hermodr for Gjallar's canonical
|
||||||
scene/control state snapshots.
|
`gamecult.eve.surface_state.v1` aggregate and hands the decoded surface to
|
||||||
|
UIKit. Hermodr is a transport/lowering boundary; it does not own layout or
|
||||||
|
provider membership.
|
||||||
- `EVEViewController` captures camera frames with AVFoundation and microphone
|
- `EVEViewController` captures camera frames with AVFoundation and microphone
|
||||||
blocks with AVAudioEngine, then sends binary CultMesh `eve-camera` and
|
blocks with AVAudioEngine, then sends binary CultMesh `eve-camera` and
|
||||||
`eve-mic` media observations to Mimir. It also renders the dashboard natively with UIKit: a scene graph,
|
`eve-mic` media observations to Mimir. It also renders the dashboard natively with UIKit: a scene graph,
|
||||||
|
|
@ -187,8 +157,8 @@ payloads as `mimir.eve_media_observation.v1`.
|
||||||
- CultNet carries typed surface state, commands, and timestamped sensor packets.
|
- CultNet carries typed surface state, commands, and timestamped sensor packets.
|
||||||
Edge JSON is tolerated only as an interoperability envelope while the typed
|
Edge JSON is tolerated only as an interoperability envelope while the typed
|
||||||
CultMesh document shape is being proven.
|
CultMesh document shape is being proven.
|
||||||
- UIKit is the current iOS streamed-frame owner; OpenGL ES is fallback/local
|
- UIKit is the current iOS `gjallar.overview` lowering owner. Streamed frames
|
||||||
render.
|
are an optional non-canonical input; OpenGL ES remains fallback/local render.
|
||||||
- The status bar stays hidden.
|
- The status bar stays hidden.
|
||||||
- Eve clients own local sensor reads and timestamps. Mimir owns synchronization
|
- Eve clients own local sensor reads and timestamps. Mimir owns synchronization
|
||||||
and final interpretation after those samples arrive.
|
and final interpretation after those samples arrive.
|
||||||
|
|
@ -214,6 +184,7 @@ See `docs/eve-dsl-reactive-bindings.md` for the first Eve DSL and reactive
|
||||||
CultMesh binding contract.
|
CultMesh binding contract.
|
||||||
See `docs/eve-multiverse.md` for the Eve MultiVerse philosophy and missing API
|
See `docs/eve-multiverse.md` for the Eve MultiVerse philosophy and missing API
|
||||||
surface.
|
surface.
|
||||||
|
See `docs/eve-persona.md` for Eve's persistent mission memory.
|
||||||
|
|
||||||
## Browser Reference
|
## Browser Reference
|
||||||
|
|
||||||
|
|
@ -246,8 +217,11 @@ render:
|
||||||
|
|
||||||
## VoidBot CEF Stream
|
## VoidBot CEF Stream
|
||||||
|
|
||||||
The CEF relay that produced these frames is not in VoidBot's default branch, so
|
Start the Starfire relay from `E:\Projects\VoidBot`:
|
||||||
no relay command is documented here until one exists.
|
|
||||||
|
```powershell
|
||||||
|
npm run swarm:eve-cef-relay -- --width 1620 --height 2160 --scale 2 --port 8792
|
||||||
|
```
|
||||||
|
|
||||||
EveCanvas displays binary JPEG frames and returns touch events only when a
|
EveCanvas displays binary JPEG frames and returns touch events only when a
|
||||||
stream lowering is configured through `EVE_STREAM_URLS`. The native app no
|
stream lowering is configured through `EVE_STREAM_URLS`. The native app no
|
||||||
|
|
@ -255,11 +229,12 @@ longer guesses a Starfire relay address.
|
||||||
|
|
||||||
## Mimir Sensor Uplink
|
## Mimir Sensor Uplink
|
||||||
|
|
||||||
Run the receiver processes from a Mimir checkout (a sibling `..\Mimir` here):
|
Start Mimir with `config/mimir-runtime.raven-eve.example.json` or run the
|
||||||
|
receiver processes directly:
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
dotnet run --project ..\Mimir\src\Mimir.EveSensorReceiver\Mimir.EveSensorReceiver.csproj -- --port 8793 --path /eve/camera --source-id eve-camera --type video-frame
|
dotnet run --project E:\Projects\Mimir\src\Mimir.EveSensorReceiver\Mimir.EveSensorReceiver.csproj -- --port 8793 --path /eve/camera --source-id eve-camera --type video-frame
|
||||||
dotnet run --project ..\Mimir\src\Mimir.EveSensorReceiver\Mimir.EveSensorReceiver.csproj -- --port 8794 --path /eve/mic --source-id eve-mic --type audio-block
|
dotnet run --project E:\Projects\Mimir\src\Mimir.EveSensorReceiver\Mimir.EveSensorReceiver.csproj -- --port 8794 --path /eve/mic --source-id eve-mic --type audio-block
|
||||||
```
|
```
|
||||||
|
|
||||||
EveCanvas sends binary `mimir.eve_media_observation.v1` camera and microphone
|
EveCanvas sends binary `mimir.eve_media_observation.v1` camera and microphone
|
||||||
|
|
@ -268,20 +243,19 @@ Periwinkle sends camera, microphone, motion, and touch observations only when
|
||||||
launched with an explicit `org.gamecult.eve.SENSOR_URI`; the apps no longer
|
launched with an explicit `org.gamecult.eve.SENSOR_URI`; the apps no longer
|
||||||
guess receiver URLs.
|
guess receiver URLs.
|
||||||
|
|
||||||
## Native Mimir Dashboard
|
## Native Gjallar Runtime
|
||||||
|
|
||||||
Start the dashboard authority on Starfire:
|
EveCanvas is the native iOS lowering of Gjallar's aggregate Eve surface. Gjallar
|
||||||
|
owns visible surface membership, order, and `weighted-bisect` layout metadata;
|
||||||
|
EveCanvas owns UIKit views, touch handling, reconnect behavior, and visible
|
||||||
|
transport failure. Odin-owned Hermodr exposes the typed CultMesh record at the
|
||||||
|
iOS HTTP boundary.
|
||||||
|
|
||||||
```powershell
|
Configure one or more Hermodr base URLs through the `EVE_HERMODR_URLS` array in
|
||||||
dotnet run --project ..\Mimir\src\Mimir.EveDashboard\Mimir.EveDashboard.csproj -- --port 8795
|
`org.gamecult.evecanvas` preferences. EveCanvas reads
|
||||||
```
|
`gjallar.overview` from `/hermodr/surface/gjallar.overview` and does not guess a
|
||||||
|
LAN address. It sends supported interactions back through
|
||||||
EveCanvas connects to the Mimir dashboard WebSocket lowering for native retained
|
`/hermodr/commands/eve`:
|
||||||
`dashboard-state` snapshots. That lowering renders the daemon-owned CultMesh
|
|
||||||
dashboard state; it is not provider discovery authority. Live provider discovery
|
|
||||||
belongs to Odin/CultMesh advertisements. Native iOS dashboard lowerings must be
|
|
||||||
configured through `EVE_DASHBOARD_URLS`; missing discovery stays visible instead
|
|
||||||
of falling back to LAN constants. EveCanvas sends compact commands back:
|
|
||||||
|
|
||||||
- `select`
|
- `select`
|
||||||
- `move`
|
- `move`
|
||||||
|
|
@ -379,14 +353,13 @@ without losing the basic app deployment path.
|
||||||
|
|
||||||
## Next Cut
|
## Next Cut
|
||||||
|
|
||||||
- Connect the existing browser reference to a clean-consumer, networked
|
- Admit live provider-owned Eve surfaces into Odin/CultMesh so Gjallar's
|
||||||
CultMesh sample and use it as the visual/behavior oracle for native clients.
|
aggregate has real children to tile; advertisements without readable surface
|
||||||
- Split the shared CultNet/CultMesh surface contract from the iOS app code and
|
state remain catalog entries, not invented UI.
|
||||||
keep `gamecult.eve.surface.v1` as the renderer-facing contract.
|
- Add native command receipts for Gjallar tiles and prove touch round trips
|
||||||
|
against provider-owned command surfaces.
|
||||||
- Replace JSON/base64 sensor packets with binary framing once camera and mic
|
- Replace JSON/base64 sensor packets with binary framing once camera and mic
|
||||||
timing are proven through Mimir.
|
timing are proven through Mimir.
|
||||||
- Replace the dashboard fixture state with live `MimirPresentationControlState`
|
|
||||||
and `MimirSceneEditorState` snapshots.
|
|
||||||
- Expand the Android Kotlin client from dashboard node rendering into the full
|
- Expand the Android Kotlin client from dashboard node rendering into the full
|
||||||
retained `surface.root` renderer, and add the browser client against the same
|
retained `surface.root` renderer, and add the browser client against the same
|
||||||
provider/sensor API.
|
provider/sensor API.
|
||||||
|
|
|
||||||
|
|
@ -1,21 +0,0 @@
|
||||||
#import <Foundation/Foundation.h>
|
|
||||||
|
|
||||||
@protocol EVEDashboardClientDelegate;
|
|
||||||
|
|
||||||
@interface EVEDashboardClient : NSObject
|
|
||||||
|
|
||||||
- (instancetype)initWithURLs:(NSArray<NSURL *> *)urls delegate:(id<EVEDashboardClientDelegate>)delegate;
|
|
||||||
- (void)connect;
|
|
||||||
- (void)disconnect;
|
|
||||||
- (void)sendCommand:(NSDictionary *)command;
|
|
||||||
|
|
||||||
@property(nonatomic, copy, readonly) NSString *status;
|
|
||||||
|
|
||||||
@end
|
|
||||||
|
|
||||||
@protocol EVEDashboardClientDelegate <NSObject>
|
|
||||||
|
|
||||||
- (void)dashboardClient:(EVEDashboardClient *)client didReceiveState:(NSDictionary *)state;
|
|
||||||
- (void)dashboardClient:(EVEDashboardClient *)client didChangeStatus:(NSString *)status;
|
|
||||||
|
|
||||||
@end
|
|
||||||
|
|
@ -1,126 +0,0 @@
|
||||||
#import "EVEDashboardClient.h"
|
|
||||||
|
|
||||||
@interface EVEDashboardClient ()
|
|
||||||
|
|
||||||
@property(nonatomic, copy) NSArray<NSURL *> *urls;
|
|
||||||
@property(nonatomic, assign) NSUInteger urlIndex;
|
|
||||||
@property(nonatomic, weak) id<EVEDashboardClientDelegate> delegate;
|
|
||||||
@property(nonatomic, strong) NSURLSession *session;
|
|
||||||
@property(nonatomic, strong) NSURLSessionWebSocketTask *task;
|
|
||||||
@property(nonatomic, assign) BOOL shouldReconnect;
|
|
||||||
@property(nonatomic, copy, readwrite) NSString *status;
|
|
||||||
|
|
||||||
@end
|
|
||||||
|
|
||||||
@implementation EVEDashboardClient
|
|
||||||
|
|
||||||
- (instancetype)initWithURLs:(NSArray<NSURL *> *)urls delegate:(id<EVEDashboardClientDelegate>)delegate {
|
|
||||||
self = [super init];
|
|
||||||
if (!self) {
|
|
||||||
return nil;
|
|
||||||
}
|
|
||||||
|
|
||||||
self.urls = urls.count > 0 ? urls : @[];
|
|
||||||
self.delegate = delegate;
|
|
||||||
self.session = [NSURLSession sessionWithConfiguration:NSURLSessionConfiguration.defaultSessionConfiguration];
|
|
||||||
self.status = @"dashboard idle";
|
|
||||||
return self;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void)connect {
|
|
||||||
self.shouldReconnect = YES;
|
|
||||||
[self.task cancelWithCloseCode:NSURLSessionWebSocketCloseCodeNormalClosure reason:nil];
|
|
||||||
NSURL *url = self.urls.count > 0 ? self.urls[self.urlIndex % self.urls.count] : nil;
|
|
||||||
if (!url) {
|
|
||||||
[self publishStatus:@"dashboard URL missing"];
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
self.task = [self.session webSocketTaskWithURL:url];
|
|
||||||
[self.task resume];
|
|
||||||
[self publishStatus:[NSString stringWithFormat:@"dashboard connecting %@", url.host ?: @""]];
|
|
||||||
[self receiveNextMessage];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void)disconnect {
|
|
||||||
self.shouldReconnect = NO;
|
|
||||||
[self.task cancelWithCloseCode:NSURLSessionWebSocketCloseCodeNormalClosure reason:nil];
|
|
||||||
self.task = nil;
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void)sendCommand:(NSDictionary *)command {
|
|
||||||
if (!self.task) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
NSData *json = [NSJSONSerialization dataWithJSONObject:command options:0 error:nil];
|
|
||||||
if (!json) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
NSString *text = [[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];
|
|
||||||
NSURLSessionWebSocketMessage *message = [[NSURLSessionWebSocketMessage alloc] initWithString:text];
|
|
||||||
[self.task sendMessage:message completionHandler:^(NSError *error) {
|
|
||||||
if (error) {
|
|
||||||
[self publishStatus:@"dashboard command failed"];
|
|
||||||
}
|
|
||||||
}];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void)receiveNextMessage {
|
|
||||||
__weak typeof(self) weakSelf = self;
|
|
||||||
[self.task receiveMessageWithCompletionHandler:^(NSURLSessionWebSocketMessage *message, NSError *error) {
|
|
||||||
__strong typeof(weakSelf) self = weakSelf;
|
|
||||||
if (!self) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (error) {
|
|
||||||
[self publishStatus:@"dashboard disconnected"];
|
|
||||||
[self reconnectSoon];
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (message.type == NSURLSessionWebSocketMessageTypeString) {
|
|
||||||
NSData *data = [message.string dataUsingEncoding:NSUTF8StringEncoding];
|
|
||||||
NSDictionary *state = data ? [NSJSONSerialization JSONObjectWithData:data options:0 error:nil] : nil;
|
|
||||||
if ([state isKindOfClass:NSDictionary.class]) {
|
|
||||||
dispatch_async(dispatch_get_main_queue(), ^{
|
|
||||||
[self.delegate dashboardClient:self didReceiveState:state];
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
[self receiveNextMessage];
|
|
||||||
}];
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void)reconnectSoon {
|
|
||||||
if (!self.shouldReconnect) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (self.urls.count > 1) {
|
|
||||||
self.urlIndex = (self.urlIndex + 1) % self.urls.count;
|
|
||||||
}
|
|
||||||
|
|
||||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
|
||||||
if (self.shouldReconnect) {
|
|
||||||
[self connect];
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void)publishStatus:(NSString *)status {
|
|
||||||
self.status = status ?: @"dashboard";
|
|
||||||
dispatch_async(dispatch_get_main_queue(), ^{
|
|
||||||
[self.delegate dashboardClient:self didChangeStatus:self.status];
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
- (void)dealloc {
|
|
||||||
[self disconnect];
|
|
||||||
[self.session invalidateAndCancel];
|
|
||||||
}
|
|
||||||
|
|
||||||
@end
|
|
||||||
28
Sources/EVEHermodrClient.h
Normal file
28
Sources/EVEHermodrClient.h
Normal file
|
|
@ -0,0 +1,28 @@
|
||||||
|
#import <Foundation/Foundation.h>
|
||||||
|
|
||||||
|
NS_ASSUME_NONNULL_BEGIN
|
||||||
|
|
||||||
|
@class EVEHermodrClient;
|
||||||
|
|
||||||
|
@protocol EVEHermodrClientDelegate <NSObject>
|
||||||
|
|
||||||
|
- (void)hermodrClient:(EVEHermodrClient *)client didReceiveSurface:(NSDictionary *)surface;
|
||||||
|
- (void)hermodrClient:(EVEHermodrClient *)client didChangeStatus:(NSString *)status;
|
||||||
|
|
||||||
|
@end
|
||||||
|
|
||||||
|
@interface EVEHermodrClient : NSObject
|
||||||
|
|
||||||
|
@property(nonatomic, copy, readonly) NSString *status;
|
||||||
|
|
||||||
|
- (instancetype)initWithBaseURLs:(NSArray<NSURL *> *)baseURLs
|
||||||
|
providerId:(NSString *)providerId
|
||||||
|
surfaceId:(NSString *)surfaceId
|
||||||
|
delegate:(id<EVEHermodrClientDelegate>)delegate;
|
||||||
|
- (void)connect;
|
||||||
|
- (void)disconnect;
|
||||||
|
- (void)sendCommand:(NSDictionary *)command;
|
||||||
|
|
||||||
|
@end
|
||||||
|
|
||||||
|
NS_ASSUME_NONNULL_END
|
||||||
192
Sources/EVEHermodrClient.m
Normal file
192
Sources/EVEHermodrClient.m
Normal file
|
|
@ -0,0 +1,192 @@
|
||||||
|
#import "EVEHermodrClient.h"
|
||||||
|
|
||||||
|
static NSTimeInterval const EVESurfaceRefreshInterval = 1.0;
|
||||||
|
|
||||||
|
@interface EVEHermodrClient ()
|
||||||
|
|
||||||
|
@property(nonatomic, copy) NSArray<NSURL *> *baseURLs;
|
||||||
|
@property(nonatomic, assign) NSUInteger urlIndex;
|
||||||
|
@property(nonatomic, copy) NSString *providerId;
|
||||||
|
@property(nonatomic, copy) NSString *surfaceId;
|
||||||
|
@property(nonatomic, weak) id<EVEHermodrClientDelegate> delegate;
|
||||||
|
@property(nonatomic, strong) NSURLSession *session;
|
||||||
|
@property(nonatomic, strong) NSURLSessionDataTask *surfaceTask;
|
||||||
|
@property(nonatomic, assign) BOOL shouldRefresh;
|
||||||
|
@property(nonatomic, assign) NSUInteger generation;
|
||||||
|
@property(nonatomic, copy) NSData *lastSurfaceData;
|
||||||
|
@property(nonatomic, copy, readwrite) NSString *status;
|
||||||
|
|
||||||
|
@end
|
||||||
|
|
||||||
|
@implementation EVEHermodrClient
|
||||||
|
|
||||||
|
- (instancetype)initWithBaseURLs:(NSArray<NSURL *> *)baseURLs
|
||||||
|
providerId:(NSString *)providerId
|
||||||
|
surfaceId:(NSString *)surfaceId
|
||||||
|
delegate:(id<EVEHermodrClientDelegate>)delegate {
|
||||||
|
self = [super init];
|
||||||
|
if (!self) {
|
||||||
|
return nil;
|
||||||
|
}
|
||||||
|
|
||||||
|
NSURLSessionConfiguration *configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration;
|
||||||
|
configuration.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
|
||||||
|
configuration.timeoutIntervalForRequest = 8.0;
|
||||||
|
configuration.timeoutIntervalForResource = 12.0;
|
||||||
|
self.session = [NSURLSession sessionWithConfiguration:configuration];
|
||||||
|
self.baseURLs = baseURLs.count > 0 ? baseURLs : @[];
|
||||||
|
self.providerId = providerId.length > 0 ? providerId : @"gjallar.overview";
|
||||||
|
self.surfaceId = surfaceId.length > 0 ? surfaceId : self.providerId;
|
||||||
|
self.delegate = delegate;
|
||||||
|
self.status = @"Hermodr idle";
|
||||||
|
return self;
|
||||||
|
}
|
||||||
|
|
||||||
|
- (void)connect {
|
||||||
|
self.shouldRefresh = YES;
|
||||||
|
self.generation += 1;
|
||||||
|
[self.surfaceTask cancel];
|
||||||
|
self.surfaceTask = nil;
|
||||||
|
self.lastSurfaceData = nil;
|
||||||
|
if (self.baseURLs.count == 0) {
|
||||||
|
[self publishStatus:@"Hermodr URL missing"];
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
[self requestSurfaceForGeneration:self.generation];
|
||||||
|
}
|
||||||
|
|
||||||
|
- (void)disconnect {
|
||||||
|
self.shouldRefresh = NO;
|
||||||
|
self.generation += 1;
|
||||||
|
[self.surfaceTask cancel];
|
||||||
|
self.surfaceTask = nil;
|
||||||
|
}
|
||||||
|
|
||||||
|
- (void)requestSurfaceForGeneration:(NSUInteger)generation {
|
||||||
|
if (!self.shouldRefresh || generation != self.generation) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
NSURL *baseURL = self.baseURLs[self.urlIndex % self.baseURLs.count];
|
||||||
|
NSURL *surfaceURL = [self surfaceURLForBaseURL:baseURL];
|
||||||
|
if (!surfaceURL) {
|
||||||
|
[self publishStatus:@"Hermodr URL invalid"];
|
||||||
|
[self scheduleRefreshForGeneration:generation];
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:surfaceURL];
|
||||||
|
request.HTTPMethod = @"GET";
|
||||||
|
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
|
||||||
|
[self publishStatus:[NSString stringWithFormat:@"opening %@", self.providerId]];
|
||||||
|
|
||||||
|
__weak typeof(self) weakSelf = self;
|
||||||
|
self.surfaceTask = [self.session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
|
||||||
|
__strong typeof(weakSelf) self = weakSelf;
|
||||||
|
if (!self || generation != self.generation || !self.shouldRefresh) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
NSHTTPURLResponse *http = [response isKindOfClass:NSHTTPURLResponse.class] ? (NSHTTPURLResponse *)response : nil;
|
||||||
|
NSError *parseError = nil;
|
||||||
|
NSDictionary *state = data.length > 0 ? [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError] : nil;
|
||||||
|
NSDictionary *surface = [state isKindOfClass:NSDictionary.class] && [state[@"surface"] isKindOfClass:NSDictionary.class] ? state[@"surface"] : nil;
|
||||||
|
NSDictionary *root = [surface[@"root"] isKindOfClass:NSDictionary.class] ? surface[@"root"] : nil;
|
||||||
|
BOOL accepted = !error && http.statusCode >= 200 && http.statusCode < 300 && root != nil;
|
||||||
|
|
||||||
|
if (accepted) {
|
||||||
|
BOOL changed = ![self.lastSurfaceData isEqualToData:data];
|
||||||
|
self.lastSurfaceData = data;
|
||||||
|
dispatch_async(dispatch_get_main_queue(), ^{
|
||||||
|
[self publishStatus:[NSString stringWithFormat:@"%@ connected", self.providerId]];
|
||||||
|
if (changed) {
|
||||||
|
[self.delegate hermodrClient:self didReceiveSurface:state];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
if (self.baseURLs.count > 1) {
|
||||||
|
self.urlIndex = (self.urlIndex + 1) % self.baseURLs.count;
|
||||||
|
}
|
||||||
|
NSString *detail = error.localizedDescription;
|
||||||
|
if (detail.length == 0 && [state[@"error"] isKindOfClass:NSString.class]) {
|
||||||
|
detail = state[@"error"];
|
||||||
|
}
|
||||||
|
if (detail.length == 0 && http) {
|
||||||
|
detail = [NSString stringWithFormat:@"HTTP %ld", (long)http.statusCode];
|
||||||
|
}
|
||||||
|
if (detail.length == 0 && parseError) {
|
||||||
|
detail = parseError.localizedDescription;
|
||||||
|
}
|
||||||
|
[self publishStatus:[NSString stringWithFormat:@"Hermodr unavailable: %@", detail ?: @"invalid surface"]];
|
||||||
|
}
|
||||||
|
[self scheduleRefreshForGeneration:generation];
|
||||||
|
}];
|
||||||
|
[self.surfaceTask resume];
|
||||||
|
}
|
||||||
|
|
||||||
|
- (void)scheduleRefreshForGeneration:(NSUInteger)generation {
|
||||||
|
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(EVESurfaceRefreshInterval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
|
||||||
|
[self requestSurfaceForGeneration:generation];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
- (NSURL *)surfaceURLForBaseURL:(NSURL *)baseURL {
|
||||||
|
NSURLComponents *components = [NSURLComponents componentsWithURL:baseURL resolvingAgainstBaseURL:NO];
|
||||||
|
if (!components.scheme.length || !components.host.length) {
|
||||||
|
return nil;
|
||||||
|
}
|
||||||
|
NSString *basePath = [components.path stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"/"]];
|
||||||
|
NSString *provider = [self.providerId stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLPathAllowedCharacterSet];
|
||||||
|
components.path = [NSString stringWithFormat:@"/%@%@hermodr/surface/%@",
|
||||||
|
basePath,
|
||||||
|
basePath.length > 0 ? @"/" : @"",
|
||||||
|
provider ?: @""];
|
||||||
|
components.queryItems = @[[NSURLQueryItem queryItemWithName:@"surfaceId" value:self.surfaceId]];
|
||||||
|
return components.URL;
|
||||||
|
}
|
||||||
|
|
||||||
|
- (NSURL *)commandURLForBaseURL:(NSURL *)baseURL {
|
||||||
|
NSURLComponents *components = [NSURLComponents componentsWithURL:baseURL resolvingAgainstBaseURL:NO];
|
||||||
|
if (!components.scheme.length || !components.host.length) {
|
||||||
|
return nil;
|
||||||
|
}
|
||||||
|
NSString *basePath = [components.path stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"/"]];
|
||||||
|
components.path = [NSString stringWithFormat:@"/%@%@hermodr/commands/eve",
|
||||||
|
basePath,
|
||||||
|
basePath.length > 0 ? @"/" : @""];
|
||||||
|
components.query = nil;
|
||||||
|
return components.URL;
|
||||||
|
}
|
||||||
|
|
||||||
|
- (void)sendCommand:(NSDictionary *)command {
|
||||||
|
if (self.baseURLs.count == 0 || ![NSJSONSerialization isValidJSONObject:command]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
NSURL *url = [self commandURLForBaseURL:self.baseURLs[self.urlIndex % self.baseURLs.count]];
|
||||||
|
if (!url) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
NSMutableDictionary *body = [command mutableCopy];
|
||||||
|
if (![body[@"providerId"] isKindOfClass:NSString.class]) {
|
||||||
|
body[@"providerId"] = self.providerId;
|
||||||
|
}
|
||||||
|
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
|
||||||
|
request.HTTPMethod = @"POST";
|
||||||
|
request.HTTPBody = [NSJSONSerialization dataWithJSONObject:body options:0 error:nil];
|
||||||
|
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
|
||||||
|
[[self.session dataTaskWithRequest:request] resume];
|
||||||
|
}
|
||||||
|
|
||||||
|
- (void)publishStatus:(NSString *)status {
|
||||||
|
self.status = status ?: @"Hermodr";
|
||||||
|
dispatch_async(dispatch_get_main_queue(), ^{
|
||||||
|
[self.delegate hermodrClient:self didChangeStatus:self.status];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
- (void)dealloc {
|
||||||
|
[self disconnect];
|
||||||
|
[self.session invalidateAndCancel];
|
||||||
|
}
|
||||||
|
|
||||||
|
@end
|
||||||
|
|
@ -4,7 +4,7 @@
|
||||||
#import <QuartzCore/QuartzCore.h>
|
#import <QuartzCore/QuartzCore.h>
|
||||||
|
|
||||||
#import "EVEFrameStreamClient.h"
|
#import "EVEFrameStreamClient.h"
|
||||||
#import "EVEDashboardClient.h"
|
#import "EVEHermodrClient.h"
|
||||||
#import "EVEGLView.h"
|
#import "EVEGLView.h"
|
||||||
#import "EVEH264StreamDecoder.h"
|
#import "EVEH264StreamDecoder.h"
|
||||||
#import "EVESensorUplinkClient.h"
|
#import "EVESensorUplinkClient.h"
|
||||||
|
|
@ -170,7 +170,7 @@ static NSArray<NSURL *> *EVEConfiguredURLs(NSString *key) {
|
||||||
return urls;
|
return urls;
|
||||||
}
|
}
|
||||||
|
|
||||||
@interface EVEViewController () <EVEFrameStreamClientDelegate, EVEDashboardClientDelegate, AVCaptureVideoDataOutputSampleBufferDelegate, UIGestureRecognizerDelegate>
|
@interface EVEViewController () <EVEFrameStreamClientDelegate, EVEHermodrClientDelegate, AVCaptureVideoDataOutputSampleBufferDelegate, UIGestureRecognizerDelegate>
|
||||||
|
|
||||||
@property(nonatomic, strong) EVEGLView *glView;
|
@property(nonatomic, strong) EVEGLView *glView;
|
||||||
@property(nonatomic, strong) UIImageView *streamImageView;
|
@property(nonatomic, strong) UIImageView *streamImageView;
|
||||||
|
|
@ -189,7 +189,7 @@ static NSArray<NSURL *> *EVEConfiguredURLs(NSString *key) {
|
||||||
@property(nonatomic, strong) CADisplayLink *displayLink;
|
@property(nonatomic, strong) CADisplayLink *displayLink;
|
||||||
@property(nonatomic, strong) CMMotionManager *motionManager;
|
@property(nonatomic, strong) CMMotionManager *motionManager;
|
||||||
@property(nonatomic, strong) EVEFrameStreamClient *streamClient;
|
@property(nonatomic, strong) EVEFrameStreamClient *streamClient;
|
||||||
@property(nonatomic, strong) EVEDashboardClient *dashboardClient;
|
@property(nonatomic, strong) EVEHermodrClient *hermodrClient;
|
||||||
@property(nonatomic, strong) EVESensorUplinkClient *cameraUplink;
|
@property(nonatomic, strong) EVESensorUplinkClient *cameraUplink;
|
||||||
@property(nonatomic, strong) EVESensorUplinkClient *micUplink;
|
@property(nonatomic, strong) EVESensorUplinkClient *micUplink;
|
||||||
@property(nonatomic, strong) AVCaptureSession *captureSession;
|
@property(nonatomic, strong) AVCaptureSession *captureSession;
|
||||||
|
|
@ -291,9 +291,12 @@ static NSArray<NSURL *> *EVEConfiguredURLs(NSString *key) {
|
||||||
self.streamClient = [[EVEFrameStreamClient alloc] initWithURLs:streamURLs delegate:self];
|
self.streamClient = [[EVEFrameStreamClient alloc] initWithURLs:streamURLs delegate:self];
|
||||||
[self.streamClient connect];
|
[self.streamClient connect];
|
||||||
|
|
||||||
NSArray<NSURL *> *dashboardURLs = EVEConfiguredURLs(@"EVE_DASHBOARD_URLS");
|
NSArray<NSURL *> *hermodrURLs = EVEConfiguredURLs(@"EVE_HERMODR_URLS");
|
||||||
self.dashboardClient = [[EVEDashboardClient alloc] initWithURLs:dashboardURLs delegate:self];
|
self.hermodrClient = [[EVEHermodrClient alloc] initWithBaseURLs:hermodrURLs
|
||||||
[self.dashboardClient connect];
|
providerId:@"gjallar.overview"
|
||||||
|
surfaceId:@"gjallar.overview"
|
||||||
|
delegate:self];
|
||||||
|
[self.hermodrClient connect];
|
||||||
|
|
||||||
NSArray<NSURL *> *cameraURLs = EVEConfiguredURLs(@"EVE_CAMERA_URLS");
|
NSArray<NSURL *> *cameraURLs = EVEConfiguredURLs(@"EVE_CAMERA_URLS");
|
||||||
NSArray<NSURL *> *micURLs = EVEConfiguredURLs(@"EVE_MIC_URLS");
|
NSArray<NSURL *> *micURLs = EVEConfiguredURLs(@"EVE_MIC_URLS");
|
||||||
|
|
@ -310,7 +313,7 @@ static NSArray<NSURL *> *EVEConfiguredURLs(NSString *key) {
|
||||||
- (void)dealloc {
|
- (void)dealloc {
|
||||||
[self.displayLink invalidate];
|
[self.displayLink invalidate];
|
||||||
[self.streamClient disconnect];
|
[self.streamClient disconnect];
|
||||||
[self.dashboardClient disconnect];
|
[self.hermodrClient disconnect];
|
||||||
[self.cameraUplink disconnect];
|
[self.cameraUplink disconnect];
|
||||||
[self.micUplink disconnect];
|
[self.micUplink disconnect];
|
||||||
[self.captureSession stopRunning];
|
[self.captureSession stopRunning];
|
||||||
|
|
@ -791,7 +794,7 @@ static NSArray<NSURL *> *EVEConfiguredURLs(NSString *key) {
|
||||||
return CGPointMake(x, y);
|
return CGPointMake(x, y);
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void)dashboardClient:(EVEDashboardClient *)client didReceiveState:(NSDictionary *)state {
|
- (void)hermodrClient:(EVEHermodrClient *)client didReceiveSurface:(NSDictionary *)state {
|
||||||
(void)client;
|
(void)client;
|
||||||
NSString *title = [state[@"title"] isKindOfClass:NSString.class] ? state[@"title"] : @"dashboard";
|
NSString *title = [state[@"title"] isKindOfClass:NSString.class] ? state[@"title"] : @"dashboard";
|
||||||
self.dashboardStatus = [NSString stringWithFormat:@"%@ v%@", title, state[@"version"] ?: @"?"];
|
self.dashboardStatus = [NSString stringWithFormat:@"%@ v%@", title, state[@"version"] ?: @"?"];
|
||||||
|
|
@ -803,10 +806,7 @@ static NSArray<NSURL *> *EVEConfiguredURLs(NSString *key) {
|
||||||
self.selectedNodeId = selected;
|
self.selectedNodeId = selected;
|
||||||
}
|
}
|
||||||
|
|
||||||
NSArray *nodes = state[@"nodes"];
|
NSArray *nodes = [state[@"nodes"] isKindOfClass:NSArray.class] ? state[@"nodes"] : @[];
|
||||||
if (![nodes isKindOfClass:NSArray.class]) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
[self.dashboardNodes removeAllObjects];
|
[self.dashboardNodes removeAllObjects];
|
||||||
NSMutableSet<NSString *> *liveNodeIds = [NSMutableSet set];
|
NSMutableSet<NSString *> *liveNodeIds = [NSMutableSet set];
|
||||||
|
|
@ -876,19 +876,7 @@ static NSArray<NSURL *> *EVEConfiguredURLs(NSString *key) {
|
||||||
- (BOOL)shouldRenderFullscreenSurfaceForState:(NSDictionary *)state {
|
- (BOOL)shouldRenderFullscreenSurfaceForState:(NSDictionary *)state {
|
||||||
NSDictionary *surface = [state[@"surface"] isKindOfClass:NSDictionary.class] ? state[@"surface"] : nil;
|
NSDictionary *surface = [state[@"surface"] isKindOfClass:NSDictionary.class] ? state[@"surface"] : nil;
|
||||||
NSDictionary *root = [surface[@"root"] isKindOfClass:NSDictionary.class] ? surface[@"root"] : nil;
|
NSDictionary *root = [surface[@"root"] isKindOfClass:NSDictionary.class] ? surface[@"root"] : nil;
|
||||||
if (!root) {
|
return root != nil;
|
||||||
return NO;
|
|
||||||
}
|
|
||||||
|
|
||||||
NSString *providerId = [state[@"providerId"] isKindOfClass:NSString.class] ? state[@"providerId"] : @"";
|
|
||||||
if ([providerId isEqualToString:@"odin.allseer"]) {
|
|
||||||
return YES;
|
|
||||||
}
|
|
||||||
|
|
||||||
NSDictionary *props = [root[@"props"] isKindOfClass:NSDictionary.class] ? root[@"props"] : nil;
|
|
||||||
NSDictionary *layout = [props[@"layout"] isKindOfClass:NSDictionary.class] ? props[@"layout"] : nil;
|
|
||||||
NSString *viewportMode = [layout[@"viewportMode"] isKindOfClass:NSString.class] ? layout[@"viewportMode"] : @"";
|
|
||||||
return [viewportMode isEqualToString:@"fullscreen"];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void)renderFullscreenSurfaceState:(NSDictionary *)state title:(NSString *)title version:(id)version {
|
- (void)renderFullscreenSurfaceState:(NSDictionary *)state title:(NSString *)title version:(id)version {
|
||||||
|
|
@ -896,8 +884,7 @@ static NSArray<NSURL *> *EVEConfiguredURLs(NSString *key) {
|
||||||
[view removeFromSuperview];
|
[view removeFromSuperview];
|
||||||
}
|
}
|
||||||
|
|
||||||
NSString *providerId = [state[@"providerId"] isKindOfClass:NSString.class] ? state[@"providerId"] : @"";
|
if ([self renderAggregateSurfaceWallForState:state]) {
|
||||||
if ([providerId isEqualToString:@"odin.allseer"] && [self renderOdinInterfaceWallForState:state]) {
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -932,7 +919,7 @@ static NSArray<NSURL *> *EVEConfiguredURLs(NSString *key) {
|
||||||
]];
|
]];
|
||||||
}
|
}
|
||||||
|
|
||||||
- (BOOL)renderOdinInterfaceWallForState:(NSDictionary *)state {
|
- (BOOL)renderAggregateSurfaceWallForState:(NSDictionary *)state {
|
||||||
[self.surfaceDashboardView layoutIfNeeded];
|
[self.surfaceDashboardView layoutIfNeeded];
|
||||||
CGRect bounds = self.surfaceDashboardView.bounds;
|
CGRect bounds = self.surfaceDashboardView.bounds;
|
||||||
if (bounds.size.width < 20.0 || bounds.size.height < 20.0) {
|
if (bounds.size.width < 20.0 || bounds.size.height < 20.0) {
|
||||||
|
|
@ -941,6 +928,11 @@ static NSArray<NSURL *> *EVEConfiguredURLs(NSString *key) {
|
||||||
|
|
||||||
NSDictionary *surface = [state[@"surface"] isKindOfClass:NSDictionary.class] ? state[@"surface"] : nil;
|
NSDictionary *surface = [state[@"surface"] isKindOfClass:NSDictionary.class] ? state[@"surface"] : nil;
|
||||||
NSDictionary *root = [surface[@"root"] isKindOfClass:NSDictionary.class] ? surface[@"root"] : nil;
|
NSDictionary *root = [surface[@"root"] isKindOfClass:NSDictionary.class] ? surface[@"root"] : nil;
|
||||||
|
NSDictionary *rootLayout = [self surfaceLayoutForElement:root];
|
||||||
|
NSString *mode = [rootLayout[@"mode"] isKindOfClass:NSString.class] ? rootLayout[@"mode"] : @"";
|
||||||
|
if (![mode isEqualToString:@"weighted-bisect"]) {
|
||||||
|
return NO;
|
||||||
|
}
|
||||||
NSArray *children = [root[@"children"] isKindOfClass:NSArray.class] ? root[@"children"] : @[];
|
NSArray *children = [root[@"children"] isKindOfClass:NSArray.class] ? root[@"children"] : @[];
|
||||||
NSMutableArray<NSDictionary *> *interfaces = [NSMutableArray array];
|
NSMutableArray<NSDictionary *> *interfaces = [NSMutableArray array];
|
||||||
for (NSDictionary *child in children) {
|
for (NSDictionary *child in children) {
|
||||||
|
|
@ -948,10 +940,10 @@ static NSArray<NSURL *> *EVEConfiguredURLs(NSString *key) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
NSString *kind = [child[@"kind"] isKindOfClass:NSString.class] ? child[@"kind"] : @"";
|
NSString *kind = [child[@"kind"] isKindOfClass:NSString.class] ? child[@"kind"] : @"";
|
||||||
NSDictionary *props = [child[@"props"] isKindOfClass:NSDictionary.class] ? child[@"props"] : @{};
|
NSDictionary *layout = [self surfaceLayoutForElement:child];
|
||||||
NSDictionary *layout = [props[@"layout"] isKindOfClass:NSDictionary.class] ? props[@"layout"] : @{};
|
id visible = layout[@"visible"];
|
||||||
NSNumber *visible = [layout[@"visible"] isKindOfClass:NSNumber.class] ? layout[@"visible"] : @YES;
|
BOOL isVisible = !visible || ![visible respondsToSelector:@selector(boolValue)] || [visible boolValue];
|
||||||
if ([kind isEqualToString:@"interface"] && visible.boolValue) {
|
if ([kind isEqualToString:@"interface"] && isVisible) {
|
||||||
[interfaces addObject:child];
|
[interfaces addObject:child];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -965,9 +957,20 @@ static NSArray<NSURL *> *EVEConfiguredURLs(NSString *key) {
|
||||||
wall.backgroundColor = [self fensalirBackdropColor];
|
wall.backgroundColor = [self fensalirBackdropColor];
|
||||||
[self.surfaceDashboardView addSubview:wall];
|
[self.surfaceDashboardView addSubview:wall];
|
||||||
|
|
||||||
CGFloat gap = 8.0;
|
if (interfaces.count == 0) {
|
||||||
|
NSDictionary *props = [root[@"props"] isKindOfClass:NSDictionary.class] ? root[@"props"] : @{};
|
||||||
|
NSString *summary = [props[@"summary"] isKindOfClass:NSString.class] ? props[@"summary"] : @"No visible Eve surfaces";
|
||||||
|
UILabel *empty = [self surfaceLabelWithText:summary size:14.0 weight:UIFontWeightMedium color:[self fensalirQuietTextColor]];
|
||||||
|
empty.frame = CGRectInset(wall.bounds, 24.0, 24.0);
|
||||||
|
empty.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
|
||||||
|
empty.textAlignment = NSTextAlignmentCenter;
|
||||||
|
[wall addSubview:empty];
|
||||||
|
return YES;
|
||||||
|
}
|
||||||
|
|
||||||
|
CGFloat gap = [rootLayout[@"gap"] respondsToSelector:@selector(doubleValue)] ? [rootLayout[@"gap"] doubleValue] : 8.0;
|
||||||
CGRect packBounds = CGRectInset(bounds, gap, gap);
|
CGRect packBounds = CGRectInset(bounds, gap, gap);
|
||||||
NSArray<NSDictionary *> *placements = [self odinPackedPlacementsForInterfaces:interfaces bounds:packBounds gap:gap];
|
NSArray<NSDictionary *> *placements = [self aggregatePlacementsForInterfaces:interfaces bounds:packBounds gap:gap];
|
||||||
for (NSDictionary *placement in placements) {
|
for (NSDictionary *placement in placements) {
|
||||||
NSDictionary *interface = [placement[@"interface"] isKindOfClass:NSDictionary.class] ? placement[@"interface"] : nil;
|
NSDictionary *interface = [placement[@"interface"] isKindOfClass:NSDictionary.class] ? placement[@"interface"] : nil;
|
||||||
NSValue *frameValue = [placement[@"frame"] isKindOfClass:NSValue.class] ? placement[@"frame"] : nil;
|
NSValue *frameValue = [placement[@"frame"] isKindOfClass:NSValue.class] ? placement[@"frame"] : nil;
|
||||||
|
|
@ -975,17 +978,18 @@ static NSArray<NSURL *> *EVEConfiguredURLs(NSString *key) {
|
||||||
if (!interface || !frameValue) {
|
if (!interface || !frameValue) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
[wall addSubview:[self odinInterfaceTile:interface frame:frameValue.CGRectValue weight:weight.doubleValue]];
|
[wall addSubview:[self aggregateInterfaceTile:interface frame:frameValue.CGRectValue weight:weight.doubleValue]];
|
||||||
}
|
}
|
||||||
|
|
||||||
return YES;
|
return YES;
|
||||||
}
|
}
|
||||||
|
|
||||||
- (NSArray<NSDictionary *> *)odinPackedPlacementsForInterfaces:(NSArray<NSDictionary *> *)interfaces bounds:(CGRect)bounds gap:(CGFloat)gap {
|
- (NSArray<NSDictionary *> *)aggregatePlacementsForInterfaces:(NSArray<NSDictionary *> *)interfaces bounds:(CGRect)bounds gap:(CGFloat)gap {
|
||||||
NSMutableArray<NSDictionary *> *items = [NSMutableArray arrayWithCapacity:interfaces.count];
|
NSMutableArray<NSDictionary *> *items = [NSMutableArray arrayWithCapacity:interfaces.count];
|
||||||
for (NSDictionary *interface in interfaces) {
|
for (NSDictionary *interface in interfaces) {
|
||||||
double weight = [self surfaceWeightForElement:interface];
|
NSDictionary *layout = [self surfaceLayoutForElement:interface];
|
||||||
[items addObject:@{@"interface": interface, @"weight": @(MAX(0.65, weight))}];
|
double weight = [layout[@"weight"] respondsToSelector:@selector(doubleValue)] ? [layout[@"weight"] doubleValue] : 1.0;
|
||||||
|
[items addObject:@{@"interface": interface, @"weight": @(MAX(0.1, weight))}];
|
||||||
}
|
}
|
||||||
[items sortUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
|
[items sortUsingComparator:^NSComparisonResult(NSDictionary *left, NSDictionary *right) {
|
||||||
double lw = [left[@"weight"] doubleValue];
|
double lw = [left[@"weight"] doubleValue];
|
||||||
|
|
@ -1000,11 +1004,11 @@ static NSArray<NSURL *> *EVEConfiguredURLs(NSString *key) {
|
||||||
}];
|
}];
|
||||||
|
|
||||||
NSMutableArray<NSDictionary *> *placements = [NSMutableArray array];
|
NSMutableArray<NSDictionary *> *placements = [NSMutableArray array];
|
||||||
[self packOdinItems:items bounds:bounds gap:gap into:placements];
|
[self packAggregateItems:items bounds:bounds gap:gap into:placements];
|
||||||
return placements;
|
return placements;
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void)packOdinItems:(NSArray<NSDictionary *> *)items bounds:(CGRect)bounds gap:(CGFloat)gap into:(NSMutableArray<NSDictionary *> *)placements {
|
- (void)packAggregateItems:(NSArray<NSDictionary *> *)items bounds:(CGRect)bounds gap:(CGFloat)gap into:(NSMutableArray<NSDictionary *> *)placements {
|
||||||
if (items.count == 0 || bounds.size.width <= 1.0 || bounds.size.height <= 1.0) {
|
if (items.count == 0 || bounds.size.width <= 1.0 || bounds.size.height <= 1.0) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
@ -1040,15 +1044,15 @@ static NSArray<NSURL *> *EVEConfiguredURLs(NSString *key) {
|
||||||
firstWidth = MAX(96.0, MIN(bounds.size.width - gap - 96.0, firstWidth));
|
firstWidth = MAX(96.0, MIN(bounds.size.width - gap - 96.0, firstWidth));
|
||||||
CGRect left = CGRectMake(bounds.origin.x, bounds.origin.y, firstWidth, bounds.size.height);
|
CGRect left = CGRectMake(bounds.origin.x, bounds.origin.y, firstWidth, bounds.size.height);
|
||||||
CGRect right = CGRectMake(CGRectGetMaxX(left) + gap, bounds.origin.y, bounds.size.width - firstWidth - gap, bounds.size.height);
|
CGRect right = CGRectMake(CGRectGetMaxX(left) + gap, bounds.origin.y, bounds.size.width - firstWidth - gap, bounds.size.height);
|
||||||
[self packOdinItems:first bounds:left gap:gap into:placements];
|
[self packAggregateItems:first bounds:left gap:gap into:placements];
|
||||||
[self packOdinItems:second bounds:right gap:gap into:placements];
|
[self packAggregateItems:second bounds:right gap:gap into:placements];
|
||||||
} else {
|
} else {
|
||||||
CGFloat firstHeight = floor((bounds.size.height - gap) * (CGFloat)ratio);
|
CGFloat firstHeight = floor((bounds.size.height - gap) * (CGFloat)ratio);
|
||||||
firstHeight = MAX(72.0, MIN(bounds.size.height - gap - 72.0, firstHeight));
|
firstHeight = MAX(72.0, MIN(bounds.size.height - gap - 72.0, firstHeight));
|
||||||
CGRect top = CGRectMake(bounds.origin.x, bounds.origin.y, bounds.size.width, firstHeight);
|
CGRect top = CGRectMake(bounds.origin.x, bounds.origin.y, bounds.size.width, firstHeight);
|
||||||
CGRect bottom = CGRectMake(bounds.origin.x, CGRectGetMaxY(top) + gap, bounds.size.width, bounds.size.height - firstHeight - gap);
|
CGRect bottom = CGRectMake(bounds.origin.x, CGRectGetMaxY(top) + gap, bounds.size.width, bounds.size.height - firstHeight - gap);
|
||||||
[self packOdinItems:first bounds:top gap:gap into:placements];
|
[self packAggregateItems:first bounds:top gap:gap into:placements];
|
||||||
[self packOdinItems:second bounds:bottom gap:gap into:placements];
|
[self packAggregateItems:second bounds:bottom gap:gap into:placements];
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -1060,31 +1064,19 @@ static NSArray<NSURL *> *EVEConfiguredURLs(NSString *key) {
|
||||||
return MAX(0.001, total);
|
return MAX(0.001, total);
|
||||||
}
|
}
|
||||||
|
|
||||||
- (double)surfaceWeightForElement:(NSDictionary *)element {
|
- (NSDictionary *)surfaceLayoutForElement:(NSDictionary *)element {
|
||||||
NSString *kind = [element[@"kind"] isKindOfClass:NSString.class] ? element[@"kind"] : @"";
|
if (![element isKindOfClass:NSDictionary.class]) {
|
||||||
|
return @{};
|
||||||
|
}
|
||||||
|
NSDictionary *layout = [element[@"layout"] isKindOfClass:NSDictionary.class] ? element[@"layout"] : nil;
|
||||||
|
if (layout) {
|
||||||
|
return layout;
|
||||||
|
}
|
||||||
NSDictionary *props = [element[@"props"] isKindOfClass:NSDictionary.class] ? element[@"props"] : @{};
|
NSDictionary *props = [element[@"props"] isKindOfClass:NSDictionary.class] ? element[@"props"] : @{};
|
||||||
NSArray *children = [element[@"children"] isKindOfClass:NSArray.class] ? element[@"children"] : @[];
|
return [props[@"layout"] isKindOfClass:NSDictionary.class] ? props[@"layout"] : @{};
|
||||||
NSString *text = [self surfaceTextForElement:element props:props fallback:@""];
|
|
||||||
double weight = [kind isEqualToString:@"interface"] ? 0.9 : 0.35;
|
|
||||||
if ([kind isEqualToString:@"text"] || [kind isEqualToString:@"metric"]) {
|
|
||||||
weight += MAX(0.22, (double)text.length / 95.0);
|
|
||||||
} else if ([kind isEqualToString:@"rail"]) {
|
|
||||||
weight += 0.55 + MIN(3.0, (double)children.count * 0.18);
|
|
||||||
} else if ([kind isEqualToString:@"card"] || [kind isEqualToString:@"pane"]) {
|
|
||||||
weight += 0.85;
|
|
||||||
} else if ([kind isEqualToString:@"dashboard"] || [kind isEqualToString:@"cockpit"]) {
|
|
||||||
weight += 0.65;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
for (NSDictionary *child in children) {
|
- (UIView *)aggregateInterfaceTile:(NSDictionary *)interface frame:(CGRect)frame weight:(double)weight {
|
||||||
if ([child isKindOfClass:NSDictionary.class]) {
|
|
||||||
weight += [self surfaceWeightForElement:child];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return MAX(0.25, weight);
|
|
||||||
}
|
|
||||||
|
|
||||||
- (UIView *)odinInterfaceTile:(NSDictionary *)interface frame:(CGRect)frame weight:(double)weight {
|
|
||||||
NSDictionary *props = [interface[@"props"] isKindOfClass:NSDictionary.class] ? interface[@"props"] : @{};
|
NSDictionary *props = [interface[@"props"] isKindOfClass:NSDictionary.class] ? interface[@"props"] : @{};
|
||||||
UIView *tile = [[UIView alloc] initWithFrame:frame];
|
UIView *tile = [[UIView alloc] initWithFrame:frame];
|
||||||
tile.backgroundColor = [self fensalirPanelColor];
|
tile.backgroundColor = [self fensalirPanelColor];
|
||||||
|
|
@ -1865,7 +1857,7 @@ static NSArray<NSURL *> *EVEConfiguredURLs(NSString *key) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void)dashboardClient:(EVEDashboardClient *)client didChangeStatus:(NSString *)status {
|
- (void)hermodrClient:(EVEHermodrClient *)client didChangeStatus:(NSString *)status {
|
||||||
(void)client;
|
(void)client;
|
||||||
self.dashboardStatus = status;
|
self.dashboardStatus = status;
|
||||||
self.dashboardStatusLabel.text = status;
|
self.dashboardStatusLabel.text = status;
|
||||||
|
|
@ -2022,7 +2014,7 @@ static NSArray<NSURL *> *EVEConfiguredURLs(NSString *key) {
|
||||||
}
|
}
|
||||||
|
|
||||||
CGFloat scale = MAX(0.25, MIN(3.0, self.activeGestureStartScale * recognizer.scale));
|
CGFloat scale = MAX(0.25, MIN(3.0, self.activeGestureStartScale * recognizer.scale));
|
||||||
[self.dashboardClient sendCommand:@{@"type": @"scale", @"nodeId": nodeId, @"scale": @(scale)}];
|
[self.hermodrClient sendCommand:@{@"type": @"scale", @"nodeId": nodeId, @"scale": @(scale)}];
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void)nodeRotated:(UIRotationGestureRecognizer *)recognizer {
|
- (void)nodeRotated:(UIRotationGestureRecognizer *)recognizer {
|
||||||
|
|
@ -2037,7 +2029,7 @@ static NSArray<NSURL *> *EVEConfiguredURLs(NSString *key) {
|
||||||
}
|
}
|
||||||
|
|
||||||
CGFloat rotation = self.activeGestureStartRotation + recognizer.rotation;
|
CGFloat rotation = self.activeGestureStartRotation + recognizer.rotation;
|
||||||
[self.dashboardClient sendCommand:@{@"type": @"rotate", @"nodeId": nodeId, @"rotation": @(rotation)}];
|
[self.hermodrClient sendCommand:@{@"type": @"rotate", @"nodeId": nodeId, @"rotation": @(rotation)}];
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void)sendMoveForNodeId:(NSString *)nodeId center:(CGPoint)center {
|
- (void)sendMoveForNodeId:(NSString *)nodeId center:(CGPoint)center {
|
||||||
|
|
@ -2045,7 +2037,7 @@ static NSArray<NSURL *> *EVEConfiguredURLs(NSString *key) {
|
||||||
CGFloat canvasHeight = MAX(1.0, self.sceneCanvasView.bounds.size.height);
|
CGFloat canvasHeight = MAX(1.0, self.sceneCanvasView.bounds.size.height);
|
||||||
CGFloat x = MIN(1.0, MAX(-1.0, (center.x / canvasWidth) * 2.0 - 1.0));
|
CGFloat x = MIN(1.0, MAX(-1.0, (center.x / canvasWidth) * 2.0 - 1.0));
|
||||||
CGFloat y = MIN(1.0, MAX(-1.0, (center.y / canvasHeight) * 2.0 - 1.0));
|
CGFloat y = MIN(1.0, MAX(-1.0, (center.y / canvasHeight) * 2.0 - 1.0));
|
||||||
[self.dashboardClient sendCommand:@{@"type": @"move", @"nodeId": nodeId, @"x": @(x), @"y": @(y)}];
|
[self.hermodrClient sendCommand:@{@"type": @"move", @"nodeId": nodeId, @"x": @(x), @"y": @(y)}];
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void)hierarchyNodePressed:(UIButton *)button {
|
- (void)hierarchyNodePressed:(UIButton *)button {
|
||||||
|
|
@ -2063,11 +2055,11 @@ static NSArray<NSURL *> *EVEConfiguredURLs(NSString *key) {
|
||||||
NSString *command = [node[@"command"] isKindOfClass:NSString.class] ? node[@"command"] : nil;
|
NSString *command = [node[@"command"] isKindOfClass:NSString.class] ? node[@"command"] : nil;
|
||||||
NSString *providerId = [node[@"providerId"] isKindOfClass:NSString.class] ? node[@"providerId"] : nil;
|
NSString *providerId = [node[@"providerId"] isKindOfClass:NSString.class] ? node[@"providerId"] : nil;
|
||||||
if ([command isEqualToString:@"open-provider"] && providerId) {
|
if ([command isEqualToString:@"open-provider"] && providerId) {
|
||||||
[self.dashboardClient sendCommand:@{@"type": @"open-provider", @"nodeId": nodeId, @"providerId": providerId}];
|
[self.hermodrClient sendCommand:@{@"type": @"open-provider", @"nodeId": nodeId, @"providerId": providerId}];
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
[self.dashboardClient sendCommand:@{@"type": @"select", @"nodeId": nodeId}];
|
[self.hermodrClient sendCommand:@{@"type": @"select", @"nodeId": nodeId}];
|
||||||
}
|
}
|
||||||
|
|
||||||
- (void)toolbarButtonPressed:(UIButton *)button {
|
- (void)toolbarButtonPressed:(UIButton *)button {
|
||||||
|
|
@ -2077,7 +2069,7 @@ static NSArray<NSURL *> *EVEConfiguredURLs(NSString *key) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
[self.dashboardClient sendCommand:@{@"type": action, @"nodeId": nodeId}];
|
[self.hermodrClient sendCommand:@{@"type": action, @"nodeId": nodeId}];
|
||||||
}
|
}
|
||||||
|
|
||||||
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
|
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
|
||||||
|
|
|
||||||
2
control
2
control
|
|
@ -2,7 +2,7 @@ Package: org.gamecult.evecanvas
|
||||||
Name: EveCanvas
|
Name: EveCanvas
|
||||||
Version: 0.1.0
|
Version: 0.1.0
|
||||||
Architecture: iphoneos-arm
|
Architecture: iphoneos-arm
|
||||||
Description: Fullscreen OpenGL ES 3.0 render shell for EVE.
|
Description: Native iOS Eve runtime for Gjallar aggregate surfaces.
|
||||||
Maintainer: GameCult <meta@gamecult.org>
|
Maintainer: GameCult <meta@gamecult.org>
|
||||||
Author: GameCult
|
Author: GameCult
|
||||||
Section: Applications
|
Section: Applications
|
||||||
|
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
[package]
|
|
||||||
name = "thing-contract"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
license = "MIT"
|
|
||||||
publish = false
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
anyhow = { workspace = true }
|
|
||||||
cultcache-rs = { workspace = true }
|
|
||||||
serde = { workspace = true }
|
|
||||||
serde_bytes = "0.11"
|
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
thing-testkit = { path = "../thing-testkit" }
|
|
||||||
rmp-serde = { workspace = true }
|
|
||||||
|
|
@ -1,39 +0,0 @@
|
||||||
//! An asset catalog: the images a provider's surfaces reference by catalog id and asset id.
|
|
||||||
|
|
||||||
use cultcache_rs::{CultSlots, DatabaseEntry};
|
|
||||||
|
|
||||||
use crate::domain::{Count, Segment, Version};
|
|
||||||
use crate::keys::{ProviderId, asset_catalog_key};
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct AssetEntry {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub id: String,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub media_type: String,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub uri: String,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub width: Count,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub height: Count,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
|
||||||
#[cultcache(type = "gamecult.thing.asset_catalog", schema = "gamecult.thing.asset_catalog.v1")]
|
|
||||||
pub struct AssetCatalog {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub provider_id: ProviderId,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub catalog_id: Segment,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub version: Version,
|
|
||||||
#[cultcache(key = 3, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.AssetEntry>")]
|
|
||||||
pub assets: Vec<AssetEntry>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl AssetCatalog {
|
|
||||||
pub fn record_key(&self) -> String {
|
|
||||||
asset_catalog_key(&self.provider_id, &self.catalog_id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,132 +0,0 @@
|
||||||
//! Commands: what a surface declares, and the one envelope a consumer sends. The caller's
|
|
||||||
//! identity has no field here: the transport sets it.
|
|
||||||
|
|
||||||
use cultcache_rs::{CultSlots, CultUnion, DatabaseEntry};
|
|
||||||
|
|
||||||
use crate::domain::Version;
|
|
||||||
use crate::keys::{CommandId, NodeId, SchemaId, invocation_key};
|
|
||||||
use crate::source::ParamName;
|
|
||||||
|
|
||||||
/// A command a surface declares. A node may reference only a declared command.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct CommandDecl {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub id: CommandId,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub payload_schema: SchemaId,
|
|
||||||
/// The input nodes whose current values travel with an invocation.
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub captures: Vec<NodeId>,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub confirm: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct CommandIdRef {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub id: CommandId,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum CommandRef {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Id(CommandIdRef),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Param(ParamName),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A typed record of the declared `payload_schema`, as its MessagePack bytes.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
#[cultcache(type_name = "GameCult.Thing.Contract.RecordPayload")]
|
|
||||||
pub struct RecordPayload {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub schema: SchemaId,
|
|
||||||
#[cultcache(key = 1, bytes)]
|
|
||||||
pub bytes: Vec<u8>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct TextValue {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct NumberValue {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct BoolValue {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct ChoiceValue {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum InputValue {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Text(TextValue),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Number(NumberValue),
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Bool(BoolValue),
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
Choice(ChoiceValue),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct CapturedInput {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub node: NodeId,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub value: InputValue,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A consumer's request that a provider run a declared command. Its fields are public, so a
|
|
||||||
/// result's copy of `invocation_id` is a convenience and not provenance: core binds results
|
|
||||||
/// to the invocations it issued.
|
|
||||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
|
||||||
#[cultcache(type = "gamecult.thing.command_invocation", schema = "gamecult.thing.command_invocation.v1")]
|
|
||||||
pub struct CommandInvocation {
|
|
||||||
/// A UUID string, unique per invocation.
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub invocation_id: String,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub surface_key: String,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub surface_version: Version,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub command: CommandId,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub payload: RecordPayload,
|
|
||||||
#[cultcache(key = 5, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.CapturedInput>")]
|
|
||||||
pub captured: Vec<CapturedInput>,
|
|
||||||
#[cultcache(key = 6)]
|
|
||||||
pub client: String,
|
|
||||||
/// RFC 3339, UTC.
|
|
||||||
#[cultcache(key = 7)]
|
|
||||||
pub issued_at: String,
|
|
||||||
#[cultcache(key = 8)]
|
|
||||||
pub delegation: Option<String>,
|
|
||||||
/// The activating node's declared id in the resolved tree. For a node inside a Repeat it is
|
|
||||||
/// the template's id, never an instance id. A confirmed invocation names the node confirmed;
|
|
||||||
/// a resumed one carries the source and items of the invocation whose result carried the effect.
|
|
||||||
#[cultcache(key = 9)]
|
|
||||||
pub source: NodeId,
|
|
||||||
/// The key of each Repeat instance enclosing the source, outermost first; empty outside any Repeat.
|
|
||||||
#[cultcache(key = 10, type_name = "System.Collections.Immutable.ImmutableArray<System.String>")]
|
|
||||||
pub items: Vec<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CommandInvocation {
|
|
||||||
pub fn record_key(&self) -> String {
|
|
||||||
invocation_key(&self.invocation_id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,237 +0,0 @@
|
||||||
//! The value domains of the contract's numbers and local names. Each domain is one field
|
|
||||||
//! type, and `new` is its only door: constructors, struct literals and every serde
|
|
||||||
//! `Deserializer` reach a value through it, so a value out of domain cannot exist.
|
|
||||||
//!
|
|
||||||
//! Each type writes and reads exactly the leaf of its inner type (`Int32`, `Int64`,
|
|
||||||
//! `String`), so the bytes are the plain leaf's. The reference's unsigned leaves are absent
|
|
||||||
//! from the TypeScript and Python packages, which is why the bound is a checked type here
|
|
||||||
//! and a refusal golden there.
|
|
||||||
|
|
||||||
use std::fmt;
|
|
||||||
|
|
||||||
use cultcache_rs::CultTypeName;
|
|
||||||
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
|
|
||||||
|
|
||||||
/// A value was outside its domain. Names the domain and its bound, never the value.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub struct DomainError {
|
|
||||||
domain: &'static str,
|
|
||||||
bound: &'static str,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl DomainError {
|
|
||||||
const fn new(domain: &'static str, bound: &'static str) -> Self {
|
|
||||||
Self { domain, bound }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The type that refused.
|
|
||||||
pub fn domain(&self) -> &'static str {
|
|
||||||
self.domain
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The bound that was not met.
|
|
||||||
pub fn bound(&self) -> &'static str {
|
|
||||||
self.bound
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl fmt::Display for DomainError {
|
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
|
||||||
write!(f, "{} must be {}", self.domain, self.bound)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl std::error::Error for DomainError {}
|
|
||||||
|
|
||||||
/// A result's position in its invocation's answers, counting from 1. `new` is the only door:
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use thing_contract::Seq;
|
|
||||||
/// assert!(Seq::new(1).is_ok());
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0423
|
|
||||||
/// use thing_contract::Seq;
|
|
||||||
/// let _ = Seq(0);
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0616
|
|
||||||
/// use thing_contract::Seq;
|
|
||||||
/// let mut seq = Seq::FIRST;
|
|
||||||
/// seq.0 = 0;
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0599
|
|
||||||
/// use thing_contract::Seq;
|
|
||||||
/// let _ = Seq::default();
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0277
|
|
||||||
/// use thing_contract::Seq;
|
|
||||||
/// let _ = Seq::from(0);
|
|
||||||
/// ```
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
|
||||||
pub struct Seq(i32);
|
|
||||||
|
|
||||||
impl CultTypeName for Seq {
|
|
||||||
fn cult_type_name() -> String {
|
|
||||||
"System.Int32".to_string()
|
|
||||||
}
|
|
||||||
const VALUE_TYPE: bool = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Seq {
|
|
||||||
pub const FIRST: Seq = Seq(1);
|
|
||||||
|
|
||||||
pub fn new(value: i32) -> Result<Self, DomainError> {
|
|
||||||
if value >= 1 { Ok(Self(value)) } else { Err(DomainError::new("Seq", "at least 1")) }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get(self) -> i32 {
|
|
||||||
self.0
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The following position; stays at `i32::MAX` rather than leaving the domain.
|
|
||||||
pub fn next(self) -> Seq {
|
|
||||||
Seq(self.0.saturating_add(1))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A document or source version, never negative. `new` is the only door:
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use thing_contract::Version;
|
|
||||||
/// assert!(Version::new(0).is_ok());
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0423
|
|
||||||
/// use thing_contract::Version;
|
|
||||||
/// let _ = Version(-1);
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0599
|
|
||||||
/// use thing_contract::Version;
|
|
||||||
/// let _ = Version::default();
|
|
||||||
/// ```
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
|
||||||
pub struct Version(i64);
|
|
||||||
|
|
||||||
impl CultTypeName for Version {
|
|
||||||
fn cult_type_name() -> String {
|
|
||||||
"System.Int64".to_string()
|
|
||||||
}
|
|
||||||
const VALUE_TYPE: bool = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Version {
|
|
||||||
pub fn new(value: i64) -> Result<Self, DomainError> {
|
|
||||||
if value >= 0 { Ok(Self(value)) } else { Err(DomainError::new("Version", "at least 0")) }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get(self) -> i64 {
|
|
||||||
self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A count, an extent or an index, never negative. `new` is the only door:
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use thing_contract::Count;
|
|
||||||
/// assert!(Count::new(0).is_ok());
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0423
|
|
||||||
/// use thing_contract::Count;
|
|
||||||
/// let _ = Count(-1);
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0277
|
|
||||||
/// use thing_contract::Count;
|
|
||||||
/// let _: Count = (-1).into();
|
|
||||||
/// ```
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
|
||||||
pub struct Count(i32);
|
|
||||||
|
|
||||||
impl Count {
|
|
||||||
pub fn new(value: i32) -> Result<Self, DomainError> {
|
|
||||||
if value >= 0 { Ok(Self(value)) } else { Err(DomainError::new("Count", "at least 0")) }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get(self) -> i32 {
|
|
||||||
self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A name the contract joins into a record key: non-empty, no `.`. `new` is the only door:
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use thing_contract::Segment;
|
|
||||||
/// assert!(Segment::new("main").is_ok());
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0423
|
|
||||||
/// use thing_contract::Segment;
|
|
||||||
/// let _ = Segment(String::from("a.b"));
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0277
|
|
||||||
/// use thing_contract::Segment;
|
|
||||||
/// let _: Segment = "a.b".into();
|
|
||||||
/// ```
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
|
||||||
pub struct Segment(String);
|
|
||||||
|
|
||||||
impl CultTypeName for Segment {
|
|
||||||
fn cult_type_name() -> String {
|
|
||||||
"System.String".to_string()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Segment {
|
|
||||||
pub fn new(value: impl Into<String>) -> Result<Self, DomainError> {
|
|
||||||
let value = value.into();
|
|
||||||
if value.is_empty() {
|
|
||||||
Err(DomainError::new("Segment", "non-empty"))
|
|
||||||
} else if value.contains('.') {
|
|
||||||
Err(DomainError::new("Segment", "free of '.'"))
|
|
||||||
} else {
|
|
||||||
Ok(Self(value))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn as_str(&self) -> &str {
|
|
||||||
&self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
macro_rules! leaf_serde {
|
|
||||||
($name:ident, $inner:ty, $serialize:ident) => {
|
|
||||||
impl Serialize for $name {
|
|
||||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
|
||||||
serializer.$serialize(self.0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'de> Deserialize<'de> for $name {
|
|
||||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
|
||||||
Self::new(<$inner>::deserialize(deserializer)?).map_err(de::Error::custom)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
leaf_serde!(Seq, i32, serialize_i32);
|
|
||||||
leaf_serde!(Version, i64, serialize_i64);
|
|
||||||
leaf_serde!(Count, i32, serialize_i32);
|
|
||||||
|
|
||||||
impl Serialize for Segment {
|
|
||||||
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
|
||||||
serializer.serialize_str(&self.0)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'de> Deserialize<'de> for Segment {
|
|
||||||
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
|
||||||
Self::new(String::deserialize(deserializer)?).map_err(de::Error::custom)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,77 +0,0 @@
|
||||||
//! Identifier newtypes and the record key of each kind. No caller spells a key as a free string.
|
|
||||||
|
|
||||||
use cultcache_rs::CultTypeName;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
use crate::domain::{Segment, Seq, Version};
|
|
||||||
|
|
||||||
macro_rules! id_type {
|
|
||||||
($(#[$doc:meta])* $name:ident) => {
|
|
||||||
$(#[$doc])*
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
|
||||||
#[serde(transparent)]
|
|
||||||
pub struct $name(String);
|
|
||||||
|
|
||||||
impl $name {
|
|
||||||
pub fn new(value: impl Into<String>) -> Self {
|
|
||||||
Self(value.into())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn as_str(&self) -> &str {
|
|
||||||
&self.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CultTypeName for $name {
|
|
||||||
fn cult_type_name() -> String {
|
|
||||||
"System.String".to_string()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
id_type!(
|
|
||||||
/// A provider of surfaces and state.
|
|
||||||
ProviderId
|
|
||||||
);
|
|
||||||
id_type!(
|
|
||||||
/// The schema id of a CultCache entry type, for example `gamecult.thing.surface.v1`.
|
|
||||||
SchemaId
|
|
||||||
);
|
|
||||||
id_type!(
|
|
||||||
/// The record key of a state record.
|
|
||||||
RecordKey
|
|
||||||
);
|
|
||||||
id_type!(
|
|
||||||
/// A node id, unique within its document after composition expansion.
|
|
||||||
NodeId
|
|
||||||
);
|
|
||||||
id_type!(
|
|
||||||
/// A command declared by a surface.
|
|
||||||
CommandId
|
|
||||||
);
|
|
||||||
|
|
||||||
// Each key joins free-string provider or publisher ids (dotted, as the Verse names them)
|
|
||||||
// with typed trailing parts: a `Segment` holds no dot and a `Seq` or `Version` is digits. A
|
|
||||||
// key therefore splits at its last dot (surface, asset catalog, result) or last two
|
|
||||||
// (composition), so two different field sets never build one key.
|
|
||||||
|
|
||||||
pub(crate) fn surface_key(provider: &ProviderId, label: &Segment) -> String {
|
|
||||||
format!("thing:surface:{}.{}", provider.as_str(), label.as_str())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn composition_key(publisher: &str, name: &Segment, version: Version) -> String {
|
|
||||||
format!("thing:composition:{publisher}.{}.v{}", name.as_str(), version.get())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn invocation_key(invocation_id: &str) -> String {
|
|
||||||
format!("thing:invocation:{invocation_id}")
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn result_key(invocation_id: &str, seq: Seq) -> String {
|
|
||||||
format!("thing:result:{invocation_id}.{}", seq.get())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn asset_catalog_key(provider: &ProviderId, catalog_id: &Segment) -> String {
|
|
||||||
format!("thing:asset_catalog:{}.{}", provider.as_str(), catalog_id.as_str())
|
|
||||||
}
|
|
||||||
|
|
@ -1,58 +0,0 @@
|
||||||
//! The `gamecult.thing.*` wire types and their bytes. This crate owns the contract: the
|
|
||||||
//! golden payloads it blesses are what every other language package and core are held to.
|
|
||||||
//!
|
|
||||||
//! Every kind is a CultCache `DatabaseEntry`; every closed set is a `CultUnion` written
|
|
||||||
//! `[armKey, [slots...]]`, the shape the C# reference reads and writes.
|
|
||||||
//!
|
|
||||||
//! Decoding is a door as well as the constructors: every kind keeps its public serde
|
|
||||||
//! `Deserialize` (CultCache's `DatabaseEntry` requires it). The domains therefore live in the
|
|
||||||
//! field types (`Seq`, `Version`, `Count`, `Segment`), whose `Deserialize` calls the same
|
|
||||||
//! `new` the constructors call, so no door skips a check.
|
|
||||||
//!
|
|
||||||
//! Stack hazard: `Node` nests without a bound of its own, and serde's `Deserialize` recurses
|
|
||||||
//! once per level, so a hostile payload nested deep enough overflows the stack of a caller that
|
|
||||||
//! decodes it directly. CultCache refuses such a payload on read and on write
|
|
||||||
//! (`cultcache_rs::check_payload_depth`, 256 containers); a caller that decodes bytes outside a
|
|
||||||
//! CultCache must run that check first.
|
|
||||||
|
|
||||||
mod asset;
|
|
||||||
mod command;
|
|
||||||
mod domain;
|
|
||||||
mod keys;
|
|
||||||
mod node;
|
|
||||||
mod result;
|
|
||||||
mod source;
|
|
||||||
mod style;
|
|
||||||
|
|
||||||
pub use asset::*;
|
|
||||||
pub use command::*;
|
|
||||||
pub use domain::{Count, DomainError, Segment, Seq, Version};
|
|
||||||
pub use keys::{CommandId, NodeId, ProviderId, RecordKey, SchemaId, asset_catalog_key};
|
|
||||||
pub use node::*;
|
|
||||||
pub use result::*;
|
|
||||||
pub use source::*;
|
|
||||||
pub use style::*;
|
|
||||||
|
|
||||||
pub use cultcache_rs::DatabaseEntry;
|
|
||||||
|
|
||||||
/// Whether `text` is an RFC 3339 UTC-or-offset date-time of the one shape a Thing timestamp is
|
|
||||||
/// written in (`YYYY-MM-DDThh:mm:ss`, an optional fraction, then `Z` or an offset). A timestamp a
|
|
||||||
/// provider publishes as text is shown as written only when this accepts it.
|
|
||||||
pub fn is_timestamp_text(text: &str) -> bool {
|
|
||||||
cultcache_rs::is_stored_at_stamp(text)
|
|
||||||
}
|
|
||||||
use cultcache_rs::{CultCache, CultCacheRegistry};
|
|
||||||
|
|
||||||
/// Registers the five kinds with a cache.
|
|
||||||
pub struct ThingContract;
|
|
||||||
|
|
||||||
impl CultCacheRegistry for ThingContract {
|
|
||||||
fn register_entries(&self, cache: &mut CultCache) -> anyhow::Result<()> {
|
|
||||||
cache.register_entry_type::<SurfaceDocument>()?;
|
|
||||||
cache.register_entry_type::<CompositionDocument>()?;
|
|
||||||
cache.register_entry_type::<CommandInvocation>()?;
|
|
||||||
cache.register_entry_type::<CommandResult>()?;
|
|
||||||
cache.register_entry_type::<AssetCatalog>()?;
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,478 +0,0 @@
|
||||||
//! Thing Script: the closed node union, the surface document that holds a tree of nodes, and the
|
|
||||||
//! composition document that names a reusable subtree. Arm keys are fixed: Slot (13) is the arm
|
|
||||||
//! added after the first twelve, and a decoder from before it refuses a record holding one
|
|
||||||
//! (CultCache's unknown-arm rule).
|
|
||||||
|
|
||||||
use cultcache_rs::{CultSlots, CultUnion, DatabaseEntry};
|
|
||||||
|
|
||||||
use crate::domain::{Count, Segment, Version};
|
|
||||||
use crate::command::{CommandDecl, CommandRef};
|
|
||||||
use crate::keys::{NodeId, ProviderId, composition_key, surface_key};
|
|
||||||
use crate::source::{Bind, BoolSource, CollectionSource, MemberPath, NumberSource, ParamName, TextSource};
|
|
||||||
use crate::style::{BoxStyle, Paint, Role};
|
|
||||||
|
|
||||||
/// What every node carries.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct NodeCommon {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub id: NodeId,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub visible: BoolSource,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub a11y_label: Option<TextSource>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
#[cultcache(type_name = "GameCult.Thing.Contract.Node")]
|
|
||||||
pub enum Node {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Box(BoxNode),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Text(TextNode),
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Image(ImageNode),
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
Button(ButtonNode),
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
Toggle(ToggleNode),
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
Slider(SliderNode),
|
|
||||||
#[cultcache(key = 6)]
|
|
||||||
TextInput(TextInputNode),
|
|
||||||
#[cultcache(key = 7)]
|
|
||||||
Select(SelectNode),
|
|
||||||
#[cultcache(key = 8)]
|
|
||||||
Repeat(RepeatNode),
|
|
||||||
#[cultcache(key = 9)]
|
|
||||||
Overlay(OverlayNode),
|
|
||||||
#[cultcache(key = 10)]
|
|
||||||
Plot(PlotNode),
|
|
||||||
#[cultcache(key = 11)]
|
|
||||||
Embed(EmbedNode),
|
|
||||||
#[cultcache(key = 12)]
|
|
||||||
Use(UseNode),
|
|
||||||
#[cultcache(key = 13)]
|
|
||||||
Slot(SlotNode),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct BoxNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub style: BoxStyle,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub paint: Paint,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub role: Role,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub children: Vec<Node>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct TextNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub content: TextSource,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub style_token: String,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub wrap: bool,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub max_lines: Option<Count>,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
pub selectable: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum ImageFit {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Contain,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Cover,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Fill,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
Unscaled,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An asset of a catalog, with the alternative text a reader without the picture needs.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct ImageNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub catalog: String,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub asset: String,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub fit: ImageFit,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub alt: TextSource,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct ButtonNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub content: Vec<Node>,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub on_activate: CommandRef,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub enabled: BoolSource,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct ToggleNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub checked: BoolSource,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub on_change: CommandRef,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct SliderNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub min: f64,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub max: f64,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub step: f64,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub value: NumberSource,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
pub commit: CommandRef,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum InputKind {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Text,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Number,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct TextInputNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub multiline: bool,
|
|
||||||
/// Named `input_kind` in every runtime (Rust `input_kind`, C# `InputKind`, TypeScript `inputKind`): a field
|
|
||||||
/// named `kind` collides with the union tag in TypeScript. The wire is the slot key, 2.
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub input_kind: InputKind,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub placeholder: TextSource,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub initial: TextSource,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
pub submit: CommandRef,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct SelectOption {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: String,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub label: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct LiteralOptions {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub options: Vec<SelectOption>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Options read from a collection: each item's value and label are members of the item.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct BoundOptions {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub collection: CollectionSource,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub value_member: MemberPath,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub label_member: MemberPath,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum OptionList {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Literal(LiteralOptions),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Bound(BoundOptions),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct SelectNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub options: OptionList,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub value: Bind,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub on_change: CommandRef,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The template is instantiated once per item of the collection, keyed by `key_member` of the item.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct RepeatNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub collection: CollectionSource,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub key_member: MemberPath,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub template: std::boxed::Box<Node>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct AnchorNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub node: NodeId,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum Anchor {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Viewport,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Node(AnchorNode),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct OverlayNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub anchor: Anchor,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub modal: bool,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub dismiss: CommandRef,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub children: Vec<Node>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum PlotMark {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Line,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Bar,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Area,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct PlotNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
/// A numeric list member of a record.
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub series: Bind,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub mark: PlotMark,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub x_min: Option<f64>,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub x_max: Option<f64>,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
pub y_min: Option<f64>,
|
|
||||||
#[cultcache(key = 6)]
|
|
||||||
pub y_max: Option<f64>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A leaf the host draws: `slot_kind` is a name the host declares it supports.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct EmbedNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub slot_kind: String,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub slot_id: String,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub width: f64,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub height: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct CompositionRef {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub publisher: String,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub name: Segment,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub version: Version,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CompositionRef {
|
|
||||||
/// The record key of the composition this names, from the one key function.
|
|
||||||
pub fn record_key(&self) -> String {
|
|
||||||
composition_key(&self.publisher, &self.name, self.version)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct UseNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub common: NodeCommon,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub composition: CompositionRef,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub args: Vec<Arg>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where a composition body places the nodes passed for its Slot parameter `param`. Only a child
|
|
||||||
/// list of a composition body holds one, and resolve refuses it elsewhere. It carries no
|
|
||||||
/// `NodeCommon`: the argument's nodes, keeping their caller-scope ids, replace it.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct SlotNode {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub param: ParamName,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct Arg {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub name: String,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub value: ArgValue,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct TextArg {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct NumberArg {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct BoolArg {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct CollectionArg {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub source: CollectionSource,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct CommandArg {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub command: CommandRef,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct SlotArg {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub nodes: Vec<Node>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum ArgValue {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Text(TextArg),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Number(NumberArg),
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Bool(BoolArg),
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
Bind(Bind),
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
Collection(CollectionArg),
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
Command(CommandArg),
|
|
||||||
#[cultcache(key = 6)]
|
|
||||||
Slot(SlotArg),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum ParamKind {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Text,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Number,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Bool,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
Bind,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
Collection,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
Command,
|
|
||||||
#[cultcache(key = 6)]
|
|
||||||
Slot,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct ParamDecl {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub name: String,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub kind: ParamKind,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A provider's surface: a tree of nodes and the commands it declares. A change of structure
|
|
||||||
/// republishes the record with a higher `version`.
|
|
||||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
|
||||||
#[cultcache(type = "gamecult.thing.surface", schema = "gamecult.thing.surface.v1")]
|
|
||||||
pub struct SurfaceDocument {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub provider_id: ProviderId,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub label: Segment,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub version: Version,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub title: String,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub root: Node,
|
|
||||||
#[cultcache(key = 5, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.CommandDecl>")]
|
|
||||||
pub commands: Vec<CommandDecl>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl SurfaceDocument {
|
|
||||||
pub fn record_key(&self) -> String {
|
|
||||||
surface_key(&self.provider_id, &self.label)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A reusable subtree with typed parameters. Compositions never own commands.
|
|
||||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
|
||||||
#[cultcache(type = "gamecult.thing.composition", schema = "gamecult.thing.composition.v1")]
|
|
||||||
pub struct CompositionDocument {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub publisher: String,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub name: Segment,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub version: Version,
|
|
||||||
#[cultcache(key = 3, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.ParamDecl>")]
|
|
||||||
pub params: Vec<ParamDecl>,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub body: Node,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CompositionDocument {
|
|
||||||
pub fn record_key(&self) -> String {
|
|
||||||
composition_key(&self.publisher, &self.name, self.version)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,231 +0,0 @@
|
||||||
//! The answer to a command invocation. A `CommandResult` is built by its four constructors,
|
|
||||||
//! each of which copies the invocation's id, and is read through accessors. Decoding is the
|
|
||||||
//! other door and holds the same domain: `seq` is a `Seq`, refused below 1 whichever door
|
|
||||||
//! it enters by. No API takes a state as a string or converts a map.
|
|
||||||
|
|
||||||
use cultcache_rs::{CultSlots, CultUnion, DatabaseEntry};
|
|
||||||
|
|
||||||
use crate::command::{CommandInvocation, CommandRef};
|
|
||||||
use crate::domain::{Seq, Version};
|
|
||||||
use crate::keys::{NodeId, result_key};
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct PendingOutcome {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub message: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct CompletedOutcome {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub source_version: Option<Version>,
|
|
||||||
/// Whether the captured drafts of the invocation clear.
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub clear_drafts: bool,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub effect: Option<Effect>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct DeniedOutcome {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub reason: String,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub node: Option<NodeId>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct FailedOutcome {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub reason: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
#[cultcache(type_name = "GameCult.Thing.Contract.Outcome")]
|
|
||||||
pub enum Outcome {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Pending(PendingOutcome),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Completed(CompletedOutcome),
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Denied(DeniedOutcome),
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
Failed(FailedOutcome),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct OpenSurfaceEffect {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub key: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct OpenExternalEffect {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub url: String,
|
|
||||||
/// The command run when the external step returns.
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub resume: CommandRef,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum Effect {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
OpenSurface(OpenSurfaceEffect),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
OpenExternal(OpenExternalEffect),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A provider's answer to one invocation. `seq` counts from 1 per invocation. The copied
|
|
||||||
/// invocation id is a convenience: core binds a result to an invocation it issued.
|
|
||||||
///
|
|
||||||
/// The positive case, a result built by a constructor from the invocation it answers:
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use thing_contract::{CommandInvocation, CommandResult, Seq};
|
|
||||||
/// fn answer(invocation: &CommandInvocation) -> CommandResult {
|
|
||||||
/// CommandResult::failed(invocation, Seq::FIRST, "refused")
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// A struct literal does not compile, because the fields are private:
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0451
|
|
||||||
/// use thing_contract::{CommandResult, FailedOutcome, Outcome, Seq};
|
|
||||||
/// let _ = CommandResult {
|
|
||||||
/// invocation_id: String::new(),
|
|
||||||
/// seq: Seq::FIRST,
|
|
||||||
/// outcome: Outcome::Failed(FailedOutcome { reason: String::new() }),
|
|
||||||
/// };
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// Each field is read through its accessor:
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use thing_contract::{CommandInvocation, CommandResult, Seq};
|
|
||||||
/// fn read(invocation: &CommandInvocation) {
|
|
||||||
/// let result = CommandResult::failed(invocation, Seq::FIRST, "refused");
|
|
||||||
/// let _ = result.invocation_id();
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// and assigning it does not compile:
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0616
|
|
||||||
/// use thing_contract::{CommandInvocation, CommandResult, Seq};
|
|
||||||
/// fn tamper(invocation: &CommandInvocation) {
|
|
||||||
/// let mut result = CommandResult::failed(invocation, Seq::FIRST, "refused");
|
|
||||||
/// result.invocation_id = String::new();
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use thing_contract::{CommandInvocation, CommandResult, Seq};
|
|
||||||
/// fn read(invocation: &CommandInvocation) {
|
|
||||||
/// let result = CommandResult::failed(invocation, Seq::FIRST, "refused");
|
|
||||||
/// let _ = result.seq();
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0616
|
|
||||||
/// use thing_contract::{CommandInvocation, CommandResult, Seq};
|
|
||||||
/// fn tamper(invocation: &CommandInvocation) {
|
|
||||||
/// let mut result = CommandResult::failed(invocation, Seq::FIRST, "refused");
|
|
||||||
/// result.seq = Seq::FIRST.next();
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use thing_contract::{CommandInvocation, CommandResult, Seq};
|
|
||||||
/// fn read(invocation: &CommandInvocation) {
|
|
||||||
/// let result = CommandResult::failed(invocation, Seq::FIRST, "refused");
|
|
||||||
/// let _ = result.outcome();
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0616
|
|
||||||
/// use thing_contract::{CommandInvocation, CommandResult, FailedOutcome, Outcome, Seq};
|
|
||||||
/// fn tamper(invocation: &CommandInvocation) {
|
|
||||||
/// let mut result = CommandResult::failed(invocation, Seq::FIRST, "refused");
|
|
||||||
/// result.outcome = Outcome::Failed(FailedOutcome { reason: String::new() });
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// Nothing converts a map into a result:
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0277
|
|
||||||
/// use std::collections::BTreeMap;
|
|
||||||
/// use thing_contract::CommandResult;
|
|
||||||
/// let flat: BTreeMap<String, String> = BTreeMap::new();
|
|
||||||
/// let _ = CommandResult::from(flat);
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// Nor a string state:
|
|
||||||
///
|
|
||||||
/// ```compile_fail,E0277
|
|
||||||
/// use thing_contract::CommandResult;
|
|
||||||
/// let _ = CommandResult::from("completed");
|
|
||||||
/// ```
|
|
||||||
#[derive(Clone, Debug, PartialEq, DatabaseEntry)]
|
|
||||||
#[cultcache(type = "gamecult.thing.command_result", schema = "gamecult.thing.command_result.v1")]
|
|
||||||
pub struct CommandResult {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
invocation_id: String,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
seq: Seq,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
outcome: Outcome,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CommandResult {
|
|
||||||
fn answering(invocation: &CommandInvocation, seq: Seq, outcome: Outcome) -> Self {
|
|
||||||
Self { invocation_id: invocation.invocation_id.clone(), seq, outcome }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn pending(invocation: &CommandInvocation, seq: Seq, message: impl Into<String>) -> Self {
|
|
||||||
Self::answering(invocation, seq, Outcome::Pending(PendingOutcome { message: message.into() }))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn completed(
|
|
||||||
invocation: &CommandInvocation,
|
|
||||||
seq: Seq,
|
|
||||||
source_version: Option<Version>,
|
|
||||||
clear_drafts: bool,
|
|
||||||
effect: Option<Effect>,
|
|
||||||
) -> Self {
|
|
||||||
Self::answering(
|
|
||||||
invocation,
|
|
||||||
seq,
|
|
||||||
Outcome::Completed(CompletedOutcome { source_version, clear_drafts, effect }),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn denied(
|
|
||||||
invocation: &CommandInvocation,
|
|
||||||
seq: Seq,
|
|
||||||
reason: impl Into<String>,
|
|
||||||
node: Option<NodeId>,
|
|
||||||
) -> Self {
|
|
||||||
Self::answering(invocation, seq, Outcome::Denied(DeniedOutcome { reason: reason.into(), node }))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn failed(invocation: &CommandInvocation, seq: Seq, reason: impl Into<String>) -> Self {
|
|
||||||
Self::answering(invocation, seq, Outcome::Failed(FailedOutcome { reason: reason.into() }))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn invocation_id(&self) -> &str {
|
|
||||||
&self.invocation_id
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn seq(&self) -> Seq {
|
|
||||||
self.seq
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn outcome(&self) -> &Outcome {
|
|
||||||
&self.outcome
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn record_key(&self) -> String {
|
|
||||||
result_key(&self.invocation_id, self.seq)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,172 +0,0 @@
|
||||||
//! Where a value comes from: a literal, a binding to a state record, or a composition parameter.
|
|
||||||
//! A member path is a list of names and indices, never an expression.
|
|
||||||
|
|
||||||
use cultcache_rs::{CultSlots, CultUnion};
|
|
||||||
|
|
||||||
use crate::domain::Count;
|
|
||||||
use crate::keys::{ProviderId, RecordKey, SchemaId};
|
|
||||||
|
|
||||||
/// A composition parameter, named.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct ParamName {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct TextLiteral {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct NumberLiteral {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct BoolLiteral {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum TextSource {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Literal(TextLiteral),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Bound(Bind),
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Param(ParamName),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum NumberSource {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Literal(NumberLiteral),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Bound(Bind),
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Param(ParamName),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum BoolSource {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Literal(BoolLiteral),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Bound(Bind),
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Param(ParamName),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One member of a record, read through a path, optionally formatted.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct Bind {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub source: StateSource,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub member: MemberPath,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub format: Option<Format>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum StateSource {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Record(StateRef),
|
|
||||||
/// The current item inside a `Repeat` template.
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Item,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A state record. An absent provider is the publisher of the document. `schema` is the id the
|
|
||||||
/// provider's record type is registered under in its store: a provider's state type must have its
|
|
||||||
/// entry type equal to that schema id, because a store names a record's schema by its entry type.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct StateRef {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub provider: Option<ProviderId>,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub schema: SchemaId,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub key: RecordKey,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct MemberPath {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub steps: Vec<MemberStep>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum MemberStep {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Name(MemberName),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Index(MemberIndex),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct MemberName {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct MemberIndex {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub index: Count,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum Format {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Number(NumberFormat),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Duration,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Timestamp,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
Affix(AffixFormat),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct NumberFormat {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub precision: Count,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub percent: bool,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub unit: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct AffixFormat {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub prefix: String,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub suffix: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The records of one type, or a list member of one record.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum CollectionSource {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Records(RecordsSource),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Member(Bind),
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Param(ParamName),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct RecordsSource {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub provider: Option<ProviderId>,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub schema: SchemaId,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub key_prefix: String,
|
|
||||||
}
|
|
||||||
|
|
@ -1,241 +0,0 @@
|
||||||
//! Box layout and paint as plain data. The crate holds no layout engine: core maps `BoxStyle`
|
|
||||||
//! onto its solver.
|
|
||||||
|
|
||||||
use cultcache_rs::{CultSlots, CultUnion};
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct Scalar {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub value: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum Dimension {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Px(Scalar),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Percent(Scalar),
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Fr(Scalar),
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
Auto,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
Content,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct Size2 {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub width: Dimension,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub height: Dimension,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct Edges {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub top: Dimension,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub right: Dimension,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub bottom: Dimension,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub left: Dimension,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum Display {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Flex,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Grid,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Block,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum Direction {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Row,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Column,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
RowReverse,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
ColumnReverse,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum Wrap {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
NoWrap,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Wrap,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
WrapReverse,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum Position {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Relative,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Absolute,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum Overflow {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Visible,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Clip,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
Scroll,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum ItemAlign {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Auto,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Start,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
End,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
Center,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
Stretch,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
Baseline,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum ContentAlign {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Auto,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Start,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
End,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
Center,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
Stretch,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
SpaceBetween,
|
|
||||||
#[cultcache(key = 6)]
|
|
||||||
SpaceAround,
|
|
||||||
#[cultcache(key = 7)]
|
|
||||||
SpaceEvenly,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The layout of a box. `gap` is the column gap in `width` and the row gap in `height`.
|
|
||||||
/// `grid_columns` and `grid_rows` are the grid tracks and are read only when `display` is Grid.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct BoxStyle {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub display: Display,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub direction: Direction,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub wrap: Wrap,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub gap: Size2,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
pub padding: Edges,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
pub margin: Edges,
|
|
||||||
#[cultcache(key = 6)]
|
|
||||||
pub size: Size2,
|
|
||||||
#[cultcache(key = 7)]
|
|
||||||
pub min_size: Size2,
|
|
||||||
#[cultcache(key = 8)]
|
|
||||||
pub max_size: Size2,
|
|
||||||
#[cultcache(key = 9)]
|
|
||||||
pub position: Position,
|
|
||||||
#[cultcache(key = 10)]
|
|
||||||
pub inset: Edges,
|
|
||||||
#[cultcache(key = 11)]
|
|
||||||
pub overflow: Overflow,
|
|
||||||
#[cultcache(key = 12)]
|
|
||||||
pub align_items: ItemAlign,
|
|
||||||
#[cultcache(key = 13)]
|
|
||||||
pub align_self: ItemAlign,
|
|
||||||
#[cultcache(key = 14)]
|
|
||||||
pub align_content: ContentAlign,
|
|
||||||
#[cultcache(key = 15)]
|
|
||||||
pub justify_content: ContentAlign,
|
|
||||||
#[cultcache(key = 16)]
|
|
||||||
pub grow: f64,
|
|
||||||
#[cultcache(key = 17)]
|
|
||||||
pub shrink: f64,
|
|
||||||
#[cultcache(key = 18)]
|
|
||||||
pub basis: Dimension,
|
|
||||||
#[cultcache(key = 19)]
|
|
||||||
pub grid_columns: Vec<Dimension>,
|
|
||||||
#[cultcache(key = 20)]
|
|
||||||
pub grid_rows: Vec<Dimension>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct ThemeToken {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct Rgba {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub r: u8,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub g: u8,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub b: u8,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
pub a: u8,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum ColorRef {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Token(ThemeToken),
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Rgba(Rgba),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct Border {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub color: ColorRef,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub width: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
|
||||||
pub struct Paint {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
pub background: Option<ColorRef>,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
pub border: Option<Border>,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
pub radius: f64,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The accessibility role of a box. The accessibility tree itself is core's.
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
|
||||||
pub enum Role {
|
|
||||||
#[cultcache(key = 0)]
|
|
||||||
Group,
|
|
||||||
#[cultcache(key = 1)]
|
|
||||||
Region,
|
|
||||||
#[cultcache(key = 2)]
|
|
||||||
List,
|
|
||||||
#[cultcache(key = 3)]
|
|
||||||
ListItem,
|
|
||||||
#[cultcache(key = 4)]
|
|
||||||
Heading,
|
|
||||||
#[cultcache(key = 5)]
|
|
||||||
Dialog,
|
|
||||||
#[cultcache(key = 6)]
|
|
||||||
Toolbar,
|
|
||||||
}
|
|
||||||
|
|
@ -1,63 +0,0 @@
|
||||||
//! The catalog rows the five document kinds publish are the rows the C# package declares:
|
|
||||||
//! `tests/thing-contract-parity/catalog-members.tsv`, which NameSetTests (C#) and parity.test.ts
|
|
||||||
//! (TypeScript) are held to as well. Schema ids differ by writer, so the comparison is by group,
|
|
||||||
//! as `catalogGroups` in parity.test.ts makes it.
|
|
||||||
|
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
use cultcache_rs::{DatabaseEntry, SchemaCatalogMember, SingleFileMessagePackBackingStore};
|
|
||||||
use thing_contract::*;
|
|
||||||
|
|
||||||
fn tsv_groups() -> Vec<String> {
|
|
||||||
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/thing-contract-parity/catalog-members.tsv");
|
|
||||||
let text = std::fs::read_to_string(path).unwrap();
|
|
||||||
let mut groups: Vec<(String, Vec<String>)> = Vec::new();
|
|
||||||
for row in text.lines().filter(|line| !line.trim().is_empty()) {
|
|
||||||
let (schema, rest) = row.split_once('\t').unwrap();
|
|
||||||
match groups.iter_mut().find(|(id, _)| id == schema) {
|
|
||||||
Some((_, rows)) => rows.push(rest.to_string()),
|
|
||||||
None => groups.push((schema.to_string(), vec![rest.to_string()])),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sorted(groups.into_iter().map(|(_, rows)| rows.join("\n")).collect())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn group(members: &[SchemaCatalogMember]) -> String {
|
|
||||||
members.iter().map(|m| format!("{}\t{}\t{}", m.slot, m.member_name, m.type_name)).collect::<Vec<_>>().join("\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn sorted(mut groups: Vec<String>) -> Vec<String> {
|
|
||||||
groups.sort();
|
|
||||||
groups
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rows_equal_the_csharp_file() {
|
|
||||||
let mine = sorted(vec![
|
|
||||||
group(&SurfaceDocument::schema_members()),
|
|
||||||
group(&CompositionDocument::schema_members()),
|
|
||||||
group(&CommandInvocation::schema_members()),
|
|
||||||
group(&CommandResult::schema_members()),
|
|
||||||
group(&AssetCatalog::schema_members()),
|
|
||||||
]);
|
|
||||||
assert_eq!(mine, tsv_groups());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn every_committed_store_carries_the_rows() {
|
|
||||||
// Each runtime's committed store, this crate's own included, declares the C# catalog. The Rust
|
|
||||||
// reader does not compare member type names when it opens a store, so a drifted name in a
|
|
||||||
// store another runtime wrote fails here. A store is copied first: reading it creates a lock
|
|
||||||
// file beside it.
|
|
||||||
for file in ["written-by-rs.cc", "written-by-cs.cc", "written-by-ts.cc"] {
|
|
||||||
let committed = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/thing-contract-parity").join(file);
|
|
||||||
let work = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!("catalog-members-{file}"));
|
|
||||||
std::fs::create_dir_all(&work).unwrap();
|
|
||||||
let copy = work.join(file);
|
|
||||||
std::fs::copy(committed, ©).unwrap();
|
|
||||||
let catalog = SingleFileMessagePackBackingStore::new(©).pull_schema_catalog().unwrap();
|
|
||||||
let from_store = sorted(catalog.iter().map(|entry| group(&entry.members)).collect());
|
|
||||||
assert_eq!(from_store, tsv_groups(), "{file}");
|
|
||||||
let _ = std::fs::remove_dir_all(&work);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,63 +0,0 @@
|
||||||
//! The stores the other two runtimes wrote. `written-by-cs.cc` and `written-by-ts.cc` in
|
|
||||||
//! `tests/thing-contract-parity` are read here, never written: each opens to exactly the five
|
|
||||||
//! records, each re-encodes to its value golden, and each sits under the key the other runtimes
|
|
||||||
//! key it by. The file is copied first: reading a store creates a lock file beside it.
|
|
||||||
|
|
||||||
use std::fmt::Debug;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
use cultcache_rs::DatabaseEntry;
|
|
||||||
use thing_contract::*;
|
|
||||||
use thing_testkit::{golden, store};
|
|
||||||
|
|
||||||
fn parity_dir() -> PathBuf {
|
|
||||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/thing-contract-parity")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn goldens_dir() -> PathBuf {
|
|
||||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn scratch(purpose: &str, bytes: &[u8]) -> PathBuf {
|
|
||||||
static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
|
||||||
let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
|
||||||
let work = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!("foreign-{purpose}-{serial}"));
|
|
||||||
std::fs::create_dir_all(&work).unwrap();
|
|
||||||
let copy = work.join("store.cc");
|
|
||||||
std::fs::write(©, bytes).unwrap();
|
|
||||||
copy
|
|
||||||
}
|
|
||||||
|
|
||||||
fn assert_record<T: DatabaseEntry + Debug>(cache: &cultcache_rs::CultCache, key: &str, golden_name: &str) {
|
|
||||||
let records = cache.get_all_with_keys::<T>().unwrap();
|
|
||||||
assert_eq!(records.len(), 1, "{golden_name}: one record of the kind");
|
|
||||||
let (found, value) = &records[0];
|
|
||||||
assert_eq!(found, key, "{golden_name}: keyed as the other runtimes key it");
|
|
||||||
let expected = golden::read(&goldens_dir(), &format!("{golden_name}.bin"));
|
|
||||||
assert_eq!(rmp_serde::to_vec(value).unwrap(), expected, "{golden_name}: re-encodes to its golden");
|
|
||||||
}
|
|
||||||
|
|
||||||
fn assert_five_records(cache: &cultcache_rs::CultCache) {
|
|
||||||
assert_record::<SurfaceDocument>(cache, "thing:surface:provider.a.main", "surface-all-arms");
|
|
||||||
assert_record::<CompositionDocument>(cache, "thing:composition:provider.a.panel.v3", "composition-all-params");
|
|
||||||
assert_record::<CommandInvocation>(cache, "thing:invocation:3f2b8c1e-5d44-4a6b-9a07-1c2d3e4f5a6b", "invocation-all-inputs");
|
|
||||||
assert_record::<CommandResult>(cache, "thing:result:3f2b8c1e-5d44-4a6b-9a07-1c2d3e4f5a6b.1", "result-pending");
|
|
||||||
assert_record::<AssetCatalog>(cache, "thing:asset_catalog:provider.a.icons", "asset-catalog");
|
|
||||||
assert_eq!(cache.snapshot().len(), 5, "no record beyond the five");
|
|
||||||
}
|
|
||||||
|
|
||||||
fn open_foreign(file: &str) {
|
|
||||||
let copy = scratch("foreign", &std::fs::read(parity_dir().join(file)).unwrap());
|
|
||||||
assert_five_records(&store::open(©));
|
|
||||||
let _ = std::fs::remove_dir_all(copy.parent().unwrap());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_store_csharp_wrote_opens_to_five_records_that_re_encode_to_the_goldens() {
|
|
||||||
open_foreign("written-by-cs.cc");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn the_store_typescript_wrote_opens_to_five_records_that_re_encode_to_the_goldens() {
|
|
||||||
open_foreign("written-by-ts.cc");
|
|
||||||
}
|
|
||||||
|
|
@ -1,685 +0,0 @@
|
||||||
//! The goldens: payload bytes written by this crate and nobody else, then compared byte for
|
|
||||||
//! byte. The TypeScript and C# packages and core are held to these files; none of them writes
|
|
||||||
//! one. `THING_BLESS=1` rewrites them; any other run compares.
|
|
||||||
|
|
||||||
use std::collections::BTreeSet;
|
|
||||||
use std::fmt::Debug;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
use thing_testkit::{build::*, golden, store};
|
|
||||||
use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry};
|
|
||||||
use thing_contract::*;
|
|
||||||
|
|
||||||
fn goldens_dir() -> PathBuf {
|
|
||||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where the stores of all three runtimes live; this crate writes `written-by-rs.cc` there.
|
|
||||||
fn parity_dir() -> PathBuf {
|
|
||||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/thing-contract-parity")
|
|
||||||
}
|
|
||||||
|
|
||||||
// A value that must never appear in a refusal.
|
|
||||||
const CANARY: &str = "CANARY-7f3a91c2";
|
|
||||||
|
|
||||||
fn golden<T: DatabaseEntry + PartialEq + Debug>(name: &str, value: &T) -> String {
|
|
||||||
let produced = rmp_serde::to_vec(value).unwrap();
|
|
||||||
let committed = golden::check(&goldens_dir(), &format!("{name}.bin"), &produced);
|
|
||||||
let decoded: T = rmp_serde::from_slice(&committed).unwrap_or_else(|error| panic!("{name}: {error}"));
|
|
||||||
assert_eq!(&decoded, value, "{name}: the golden does not decode to the constructed value");
|
|
||||||
assert_eq!(rmp_serde::to_vec(&decoded).unwrap(), committed, "{name}: re-encoding changed the bytes");
|
|
||||||
name.to_string()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn bind_all_formats() -> Vec<Bind> {
|
|
||||||
let number = Format::Number(NumberFormat { precision: count(2), percent: true, unit: Some("ms".into()) });
|
|
||||||
let affix = Format::Affix(AffixFormat { prefix: "$".into(), suffix: "/s".into() });
|
|
||||||
let indexed = MemberPath {
|
|
||||||
steps: vec![
|
|
||||||
MemberStep::Name(MemberName { name: "items".into() }),
|
|
||||||
MemberStep::Index(MemberIndex { index: count(3) }),
|
|
||||||
],
|
|
||||||
};
|
|
||||||
vec![
|
|
||||||
record_bind(indexed, Some(number)),
|
|
||||||
record_bind(path(&["elapsed"]), Some(Format::Duration)),
|
|
||||||
record_bind(path(&["at"]), Some(Format::Timestamp)),
|
|
||||||
record_bind(path(&["price"]), Some(affix)),
|
|
||||||
record_bind(path(&["plain"]), None),
|
|
||||||
item_bind(path(&["name"])),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A surface using all 13 node arms, nested more than four deep, with every source arm.
|
|
||||||
fn full_surface() -> SurfaceDocument {
|
|
||||||
let binds = bind_all_formats();
|
|
||||||
let bound_text = TextSource::Bound(binds[3].clone());
|
|
||||||
let bound_bool = BoolSource::Bound(binds[4].clone());
|
|
||||||
let bound_number = NumberSource::Bound(binds[0].clone());
|
|
||||||
|
|
||||||
let mut painted = BoxNode {
|
|
||||||
common: NodeCommon {
|
|
||||||
id: nid("painted"),
|
|
||||||
visible: BoolSource::Param(param("show")),
|
|
||||||
a11y_label: Some(TextSource::Param(param("label"))),
|
|
||||||
},
|
|
||||||
style: style(),
|
|
||||||
paint: Paint {
|
|
||||||
background: Some(ColorRef::Token(ThemeToken { name: "surface.raised".into() })),
|
|
||||||
border: Some(Border { color: ColorRef::Rgba(Rgba { r: 1, g: 2, b: 3, a: 255 }), width: 1.5 }),
|
|
||||||
radius: 4.0,
|
|
||||||
},
|
|
||||||
role: Role::Region,
|
|
||||||
children: vec![],
|
|
||||||
};
|
|
||||||
painted.style.display = Display::Grid;
|
|
||||||
painted.style.grid_columns = vec![Dimension::Fr(Scalar { value: 1.0 }), px(120.0)];
|
|
||||||
painted.style.grid_rows = vec![Dimension::Content];
|
|
||||||
painted.style.position = Position::Absolute;
|
|
||||||
painted.style.overflow = Overflow::Scroll;
|
|
||||||
painted.style.direction = Direction::RowReverse;
|
|
||||||
painted.style.wrap = Wrap::WrapReverse;
|
|
||||||
painted.style.align_items = ItemAlign::Baseline;
|
|
||||||
painted.style.align_self = ItemAlign::Center;
|
|
||||||
painted.style.align_content = ContentAlign::SpaceAround;
|
|
||||||
painted.style.justify_content = ContentAlign::SpaceEvenly;
|
|
||||||
painted.children = vec![text("deep-text", "deep")];
|
|
||||||
|
|
||||||
let repeat = Node::Repeat(RepeatNode {
|
|
||||||
common: common("rows"),
|
|
||||||
collection: CollectionSource::Records(RecordsSource {
|
|
||||||
provider: None,
|
|
||||||
schema: SchemaId::new("gamecult.thing.test.v1"),
|
|
||||||
key_prefix: "row-".into(),
|
|
||||||
}),
|
|
||||||
key_member: path(&["id"]),
|
|
||||||
template: std::boxed::Box::new(Node::Text(TextNode {
|
|
||||||
common: common("row-name"),
|
|
||||||
content: TextSource::Bound(item_bind(path(&["name"]))),
|
|
||||||
style_token: "body".into(),
|
|
||||||
wrap: false,
|
|
||||||
max_lines: Some(count(2)),
|
|
||||||
selectable: true,
|
|
||||||
})),
|
|
||||||
});
|
|
||||||
|
|
||||||
let leaves = vec![
|
|
||||||
Node::Text(TextNode {
|
|
||||||
common: common("t-bound"),
|
|
||||||
content: bound_text,
|
|
||||||
style_token: "label".into(),
|
|
||||||
wrap: true,
|
|
||||||
max_lines: None,
|
|
||||||
selectable: false,
|
|
||||||
}),
|
|
||||||
Node::Image(ImageNode {
|
|
||||||
common: common("img"),
|
|
||||||
catalog: "icons".into(),
|
|
||||||
asset: "gear".into(),
|
|
||||||
fit: ImageFit::Cover,
|
|
||||||
alt: lit_text("a gear"),
|
|
||||||
}),
|
|
||||||
Node::Button(ButtonNode {
|
|
||||||
common: common("go"),
|
|
||||||
content: vec![text("go-label", "Go")],
|
|
||||||
on_activate: command("go"),
|
|
||||||
enabled: bound_bool.clone(),
|
|
||||||
}),
|
|
||||||
Node::Toggle(ToggleNode { common: common("flag"), checked: bound_bool, on_change: CommandRef::Param(param("toggle")) }),
|
|
||||||
Node::Slider(SliderNode {
|
|
||||||
common: common("level"),
|
|
||||||
min: 0.0,
|
|
||||||
max: 1.0,
|
|
||||||
step: 0.25,
|
|
||||||
value: bound_number,
|
|
||||||
commit: command("set-level"),
|
|
||||||
}),
|
|
||||||
Node::TextInput(TextInputNode {
|
|
||||||
common: common("name-input"),
|
|
||||||
multiline: true,
|
|
||||||
input_kind: InputKind::Number,
|
|
||||||
placeholder: lit_text("name"),
|
|
||||||
initial: TextSource::Param(param("initial")),
|
|
||||||
submit: command("rename"),
|
|
||||||
}),
|
|
||||||
Node::TextInput(TextInputNode {
|
|
||||||
common: common("title-input"),
|
|
||||||
multiline: false,
|
|
||||||
input_kind: InputKind::Text,
|
|
||||||
placeholder: lit_text("title"),
|
|
||||||
initial: TextSource::Param(param("initial")),
|
|
||||||
submit: command("retitle"),
|
|
||||||
}),
|
|
||||||
Node::Select(SelectNode {
|
|
||||||
common: common("pick"),
|
|
||||||
options: OptionList::Literal(LiteralOptions {
|
|
||||||
options: vec![SelectOption { value: "a".into(), label: "Alpha".into() }],
|
|
||||||
}),
|
|
||||||
value: binds[4].clone(),
|
|
||||||
on_change: command("pick"),
|
|
||||||
}),
|
|
||||||
Node::Select(SelectNode {
|
|
||||||
common: common("pick-bound"),
|
|
||||||
options: OptionList::Bound(BoundOptions {
|
|
||||||
collection: CollectionSource::Member(binds[0].clone()),
|
|
||||||
value_member: path(&["id"]),
|
|
||||||
label_member: path(&["name"]),
|
|
||||||
}),
|
|
||||||
value: binds[5].clone(),
|
|
||||||
on_change: command("pick"),
|
|
||||||
}),
|
|
||||||
repeat,
|
|
||||||
Node::Overlay(OverlayNode {
|
|
||||||
common: common("menu"),
|
|
||||||
anchor: Anchor::Node(AnchorNode { node: nid("go") }),
|
|
||||||
modal: false,
|
|
||||||
dismiss: command("close"),
|
|
||||||
children: vec![text("menu-item", "one")],
|
|
||||||
}),
|
|
||||||
Node::Overlay(OverlayNode {
|
|
||||||
common: common("dialog"),
|
|
||||||
anchor: Anchor::Viewport,
|
|
||||||
modal: true,
|
|
||||||
dismiss: command("close"),
|
|
||||||
children: vec![],
|
|
||||||
}),
|
|
||||||
Node::Plot(PlotNode {
|
|
||||||
common: common("trend"),
|
|
||||||
series: binds[1].clone(),
|
|
||||||
mark: PlotMark::Area,
|
|
||||||
x_min: Some(0.0),
|
|
||||||
x_max: None,
|
|
||||||
y_min: None,
|
|
||||||
y_max: Some(100.0),
|
|
||||||
}),
|
|
||||||
Node::Embed(EmbedNode {
|
|
||||||
common: common("viewport"),
|
|
||||||
slot_kind: "world.scene".into(),
|
|
||||||
slot_id: "main".into(),
|
|
||||||
width: 640.0,
|
|
||||||
height: 480.0,
|
|
||||||
}),
|
|
||||||
Node::Use(UseNode {
|
|
||||||
common: common("kv"),
|
|
||||||
composition: CompositionRef { publisher: "thing.std".into(), name: seg("key-value"), version: ver(1) },
|
|
||||||
args: vec![Arg { name: "key".into(), value: ArgValue::Text(TextArg { value: "k".into() }) }],
|
|
||||||
}),
|
|
||||||
];
|
|
||||||
|
|
||||||
let mut deep = boxed("d4", vec![Node::Box(painted)]);
|
|
||||||
for id in ["d3", "d2", "d1"] {
|
|
||||||
deep = boxed(id, vec![deep]);
|
|
||||||
}
|
|
||||||
let mut children = vec![deep];
|
|
||||||
children.extend(leaves);
|
|
||||||
for plot_choice in [
|
|
||||||
Node::Plot(PlotNode {
|
|
||||||
common: common("trend-line"),
|
|
||||||
series: binds[2].clone(),
|
|
||||||
mark: PlotMark::Line,
|
|
||||||
x_min: None,
|
|
||||||
x_max: None,
|
|
||||||
y_min: None,
|
|
||||||
y_max: None,
|
|
||||||
}),
|
|
||||||
Node::Plot(PlotNode {
|
|
||||||
common: common("trend-bar"),
|
|
||||||
series: binds[2].clone(),
|
|
||||||
mark: PlotMark::Bar,
|
|
||||||
x_min: None,
|
|
||||||
x_max: None,
|
|
||||||
y_min: None,
|
|
||||||
y_max: None,
|
|
||||||
}),
|
|
||||||
] {
|
|
||||||
children.push(plot_choice);
|
|
||||||
}
|
|
||||||
for (index, fit) in [ImageFit::Contain, ImageFit::Fill, ImageFit::Unscaled].into_iter().enumerate() {
|
|
||||||
children.push(Node::Image(ImageNode {
|
|
||||||
common: common(&format!("img-fit-{index}")),
|
|
||||||
catalog: "icons".into(),
|
|
||||||
asset: "gear".into(),
|
|
||||||
fit,
|
|
||||||
alt: lit_text(""),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
for (index, role) in [Role::List, Role::ListItem, Role::Heading, Role::Dialog, Role::Toolbar].into_iter().enumerate() {
|
|
||||||
let mut role_style = style();
|
|
||||||
if index == 0 {
|
|
||||||
role_style.direction = Direction::Row;
|
|
||||||
role_style.align_content = ContentAlign::Auto;
|
|
||||||
role_style.justify_content = ContentAlign::Stretch;
|
|
||||||
}
|
|
||||||
children.push(Node::Box(BoxNode {
|
|
||||||
common: common(&format!("role-{index}")),
|
|
||||||
style: role_style,
|
|
||||||
paint: plain_paint(),
|
|
||||||
role,
|
|
||||||
children: vec![],
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
let mut block = BoxNode {
|
|
||||||
common: common("block"),
|
|
||||||
style: style(),
|
|
||||||
paint: plain_paint(),
|
|
||||||
role: Role::Group,
|
|
||||||
children: vec![],
|
|
||||||
};
|
|
||||||
block.style.display = Display::Block;
|
|
||||||
block.style.direction = Direction::ColumnReverse;
|
|
||||||
block.style.wrap = Wrap::Wrap;
|
|
||||||
block.style.overflow = Overflow::Clip;
|
|
||||||
block.style.align_content = ContentAlign::Center;
|
|
||||||
block.style.justify_content = ContentAlign::End;
|
|
||||||
block.style.align_items = ItemAlign::End;
|
|
||||||
block.style.align_self = ItemAlign::Start;
|
|
||||||
block.style.basis = Dimension::Content;
|
|
||||||
children.push(Node::Box(block));
|
|
||||||
children.push(Node::Text(TextNode {
|
|
||||||
common: common("t-param"),
|
|
||||||
content: TextSource::Param(param("title")),
|
|
||||||
style_token: "title".into(),
|
|
||||||
wrap: true,
|
|
||||||
max_lines: None,
|
|
||||||
selectable: false,
|
|
||||||
}));
|
|
||||||
children.push(Node::Toggle(ToggleNode {
|
|
||||||
common: NodeCommon { id: nid("literal-number"), visible: BoolSource::Param(param("v")), a11y_label: None },
|
|
||||||
checked: lit_bool(false),
|
|
||||||
on_change: command("toggle"),
|
|
||||||
}));
|
|
||||||
children.push(Node::Slider(SliderNode {
|
|
||||||
common: common("slider-literal"),
|
|
||||||
min: -1.0,
|
|
||||||
max: 1.0,
|
|
||||||
step: 0.5,
|
|
||||||
value: lit_number(0.5),
|
|
||||||
commit: command("set-level"),
|
|
||||||
}));
|
|
||||||
children.push(Node::Slider(SliderNode {
|
|
||||||
common: common("slider-param"),
|
|
||||||
min: 0.0,
|
|
||||||
max: 10.0,
|
|
||||||
step: 1.0,
|
|
||||||
value: NumberSource::Param(param("n")),
|
|
||||||
commit: command("set-level"),
|
|
||||||
}));
|
|
||||||
children.push(Node::Repeat(RepeatNode {
|
|
||||||
common: common("rows-param"),
|
|
||||||
collection: CollectionSource::Param(param("rows")),
|
|
||||||
key_member: path(&["id"]),
|
|
||||||
template: std::boxed::Box::new(text("row-param", "r")),
|
|
||||||
}));
|
|
||||||
|
|
||||||
SurfaceDocument {
|
|
||||||
provider_id: ProviderId::new("provider.a"),
|
|
||||||
label: seg("main"),
|
|
||||||
version: ver(7),
|
|
||||||
title: "All arms".into(),
|
|
||||||
root: boxed("root", children),
|
|
||||||
commands: vec![
|
|
||||||
CommandDecl {
|
|
||||||
id: CommandId::new("go"),
|
|
||||||
payload_schema: SchemaId::new("gamecult.thing.test.go.v1"),
|
|
||||||
captures: vec![nid("name-input"), nid("level")],
|
|
||||||
confirm: Some("Go now?".into()),
|
|
||||||
},
|
|
||||||
CommandDecl {
|
|
||||||
id: CommandId::new("close"),
|
|
||||||
payload_schema: SchemaId::new("gamecult.thing.test.close.v1"),
|
|
||||||
captures: vec![],
|
|
||||||
confirm: None,
|
|
||||||
},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn full_composition() -> CompositionDocument {
|
|
||||||
let args = vec![
|
|
||||||
Arg { name: "text".into(), value: ArgValue::Text(TextArg { value: "t".into() }) },
|
|
||||||
Arg { name: "number".into(), value: ArgValue::Number(NumberArg { value: 2.5 }) },
|
|
||||||
Arg { name: "bool".into(), value: ArgValue::Bool(BoolArg { value: true }) },
|
|
||||||
Arg { name: "bind".into(), value: ArgValue::Bind(record_bind(path(&["x"]), None)) },
|
|
||||||
Arg {
|
|
||||||
name: "collection".into(),
|
|
||||||
value: ArgValue::Collection(CollectionArg { source: CollectionSource::Param(param("rows")) }),
|
|
||||||
},
|
|
||||||
Arg { name: "command".into(), value: ArgValue::Command(CommandArg { command: command("go") }) },
|
|
||||||
Arg {
|
|
||||||
name: "slot".into(),
|
|
||||||
value: ArgValue::Slot(SlotArg { nodes: vec![text("slot-text", "inside"), boxed("slot-box", vec![])] }),
|
|
||||||
},
|
|
||||||
];
|
|
||||||
let inner_use = Node::Use(UseNode {
|
|
||||||
common: common("inner"),
|
|
||||||
composition: CompositionRef { publisher: "thing.std".into(), name: seg("card"), version: ver(2) },
|
|
||||||
args,
|
|
||||||
});
|
|
||||||
CompositionDocument {
|
|
||||||
publisher: "provider.a".into(),
|
|
||||||
name: seg("panel"),
|
|
||||||
version: ver(3),
|
|
||||||
params: [
|
|
||||||
("title", ParamKind::Text),
|
|
||||||
("count", ParamKind::Number),
|
|
||||||
("on", ParamKind::Bool),
|
|
||||||
("source", ParamKind::Bind),
|
|
||||||
("rows", ParamKind::Collection),
|
|
||||||
("act", ParamKind::Command),
|
|
||||||
("body", ParamKind::Slot),
|
|
||||||
]
|
|
||||||
.into_iter()
|
|
||||||
.map(|(name, kind)| ParamDecl { name: name.into(), kind })
|
|
||||||
.collect(),
|
|
||||||
body: boxed(
|
|
||||||
"panel-root",
|
|
||||||
vec![text("panel-title", "t"), inner_use, Node::Slot(SlotNode { param: param("body") })],
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn results(invocation: &CommandInvocation) -> Vec<(&'static str, CommandResult)> {
|
|
||||||
vec![
|
|
||||||
("result-pending", CommandResult::pending(invocation, seq(1), "working")),
|
|
||||||
("result-completed", CommandResult::completed(invocation, seq(2), Some(ver(8)), true, None)),
|
|
||||||
(
|
|
||||||
"result-completed-open-surface",
|
|
||||||
CommandResult::completed(
|
|
||||||
invocation,
|
|
||||||
seq(3),
|
|
||||||
None,
|
|
||||||
false,
|
|
||||||
Some(Effect::OpenSurface(OpenSurfaceEffect { key: "thing:surface:provider.a.next".into() })),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
"result-completed-open-external",
|
|
||||||
CommandResult::completed(
|
|
||||||
invocation,
|
|
||||||
seq(4),
|
|
||||||
Some(ver(9)),
|
|
||||||
true,
|
|
||||||
Some(Effect::OpenExternal(OpenExternalEffect {
|
|
||||||
url: "https://example.test/auth".into(),
|
|
||||||
resume: command("resume"),
|
|
||||||
})),
|
|
||||||
),
|
|
||||||
),
|
|
||||||
("result-denied", CommandResult::denied(invocation, seq(5), "not yours", Some(nid("go")))),
|
|
||||||
("result-denied-no-node", CommandResult::denied(invocation, seq(6), "not allowed", None)),
|
|
||||||
("result-failed", CommandResult::failed(invocation, seq(7), "broke")),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
fn asset_catalog() -> AssetCatalog {
|
|
||||||
AssetCatalog {
|
|
||||||
provider_id: ProviderId::new("provider.a"),
|
|
||||||
catalog_id: seg("icons"),
|
|
||||||
version: ver(2),
|
|
||||||
assets: vec![
|
|
||||||
AssetEntry { id: "gear".into(), media_type: "image/png".into(), uri: "assets/gear.png".into(), width: count(32), height: count(32) },
|
|
||||||
AssetEntry { id: "bolt".into(), media_type: "image/svg+xml".into(), uri: "assets/bolt.svg".into(), width: count(0), height: count(0) },
|
|
||||||
],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A store with one record of each kind, written by cultcache-rs under a pinned clock.
|
|
||||||
fn write_store(path: &std::path::Path) {
|
|
||||||
let mut cache = store::create(path);
|
|
||||||
let surface = full_surface();
|
|
||||||
let composition = full_composition();
|
|
||||||
let invocation = invocation();
|
|
||||||
let result = CommandResult::pending(&invocation, seq(1), "working");
|
|
||||||
let catalog = asset_catalog();
|
|
||||||
store::put_pinned(&mut cache, &surface.record_key(), &surface);
|
|
||||||
store::put_pinned(&mut cache, &composition.record_key(), &composition);
|
|
||||||
store::put_pinned(&mut cache, &invocation.record_key(), &invocation);
|
|
||||||
store::put_pinned(&mut cache, &result.record_key(), &result);
|
|
||||||
store::put_pinned(&mut cache, &catalog.record_key(), &catalog);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn envelope<T: DatabaseEntry>(key: &str, payload: Vec<u8>) -> CultCacheEnvelope {
|
|
||||||
CultCacheEnvelope {
|
|
||||||
key: key.into(),
|
|
||||||
r#type: T::TYPE.into(),
|
|
||||||
payload,
|
|
||||||
stored_at: store::PINNED_CLOCK.into(),
|
|
||||||
schema_id: Some(T::TYPE.into()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn slot_arm_bytes() {
|
|
||||||
let slot = Node::Slot(SlotNode { param: param("body") });
|
|
||||||
let bytes = rmp_serde::to_vec(&slot).unwrap();
|
|
||||||
assert_eq!(bytes, [0x92, 0x0D, 0x91, 0x91, 0xA4, 0x62, 0x6F, 0x64, 0x79]);
|
|
||||||
assert_eq!(rmp_serde::from_slice::<Node>(&bytes).unwrap(), slot);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn goldens_match() {
|
|
||||||
let mut names = BTreeSet::new();
|
|
||||||
names.insert(golden("surface-all-arms", &full_surface()));
|
|
||||||
names.insert(golden("composition-all-params", &full_composition()));
|
|
||||||
let invocation = invocation();
|
|
||||||
names.insert(golden("invocation-all-inputs", &invocation));
|
|
||||||
for (name, result) in results(&invocation) {
|
|
||||||
names.insert(golden(name, &result));
|
|
||||||
}
|
|
||||||
names.insert(golden("asset-catalog", &asset_catalog()));
|
|
||||||
|
|
||||||
// The refusal and tolerance goldens are written by `refusal_payloads` below; a stale file
|
|
||||||
// that no case names is an orphan.
|
|
||||||
let refusals = refusal_payloads();
|
|
||||||
for (name, bytes) in &refusals {
|
|
||||||
golden::check(&goldens_dir(), &format!("{name}.bin"), bytes);
|
|
||||||
names.insert((*name).to_string());
|
|
||||||
}
|
|
||||||
let on_disk: BTreeSet<String> = std::fs::read_dir(goldens_dir())
|
|
||||||
.unwrap()
|
|
||||||
.filter_map(|entry| entry.unwrap().file_name().into_string().ok())
|
|
||||||
.filter_map(|file| file.strip_suffix(".bin").map(str::to_string))
|
|
||||||
.collect();
|
|
||||||
assert_eq!(on_disk, names, "every .bin golden is a named case and every case has its file");
|
|
||||||
|
|
||||||
// The store: one record of each kind, written under a pinned clock, byte for byte.
|
|
||||||
let scratch = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("goldens-surface.cc");
|
|
||||||
write_store(&scratch);
|
|
||||||
let parity = parity_dir();
|
|
||||||
let committed = golden::check(&parity, "written-by-rs.cc", &std::fs::read(&scratch).unwrap());
|
|
||||||
let reopened = parity.join("written-by-rs.cc");
|
|
||||||
assert_eq!(std::fs::read(&reopened).unwrap(), committed);
|
|
||||||
let cache = store::open(&scratch);
|
|
||||||
let surface = full_surface();
|
|
||||||
assert_eq!(cache.get::<SurfaceDocument>(&surface.record_key()).unwrap(), Some(surface));
|
|
||||||
let composition = full_composition();
|
|
||||||
assert_eq!(cache.get::<CompositionDocument>(&composition.record_key()).unwrap(), Some(composition));
|
|
||||||
assert_eq!(cache.get::<CommandInvocation>(&invocation.record_key()).unwrap(), Some(invocation.clone()));
|
|
||||||
let result = CommandResult::pending(&invocation, seq(1), "working");
|
|
||||||
assert_eq!(cache.get::<CommandResult>(&result.record_key()).unwrap(), Some(result));
|
|
||||||
let catalog = asset_catalog();
|
|
||||||
assert_eq!(cache.get::<AssetCatalog>(&catalog.record_key()).unwrap(), Some(catalog));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The foreign and malformed payloads. Each is the bytes a consumer might send; none is a
|
|
||||||
/// value of this crate, so each is spelled from MessagePack tuples and maps.
|
|
||||||
fn refusal_payloads() -> Vec<(&'static str, Vec<u8>)> {
|
|
||||||
// The map a Thing 1 provider writes for a command result: named members, a receipt
|
|
||||||
// inside, no positional slots.
|
|
||||||
#[derive(serde::Serialize)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
struct Receipt {
|
|
||||||
command_id: &'static str,
|
|
||||||
command: &'static str,
|
|
||||||
state: &'static str,
|
|
||||||
message: &'static str,
|
|
||||||
source_version: u64,
|
|
||||||
issued_at_utc: &'static str,
|
|
||||||
}
|
|
||||||
#[derive(serde::Serialize)]
|
|
||||||
struct Flat {
|
|
||||||
receipt: Receipt,
|
|
||||||
}
|
|
||||||
let flat = Flat {
|
|
||||||
receipt: Receipt {
|
|
||||||
command_id: "inv-1",
|
|
||||||
command: "go",
|
|
||||||
state: "completed",
|
|
||||||
message: CANARY,
|
|
||||||
source_version: 4,
|
|
||||||
issued_at_utc: "2026-01-01T00:00:00Z",
|
|
||||||
},
|
|
||||||
};
|
|
||||||
let unit: [u8; 0] = [];
|
|
||||||
let pending = Outcome::Pending(PendingOutcome { message: CANARY.into() });
|
|
||||||
let root = text("root", "x");
|
|
||||||
vec![
|
|
||||||
("result-thing1-flat", rmp_serde::to_vec_named(&flat).unwrap()),
|
|
||||||
// A surface whose root is an arm key the Node union does not declare: 14 is the first key
|
|
||||||
// Node does not declare (Slot is 13).
|
|
||||||
(
|
|
||||||
"node-unknown-arm",
|
|
||||||
rmp_serde::to_vec(&("provider.a", "main", 1i64, CANARY, (14i32, (CANARY,)), unit)).unwrap(),
|
|
||||||
),
|
|
||||||
// A result whose outcome is an arm key the Outcome union does not declare.
|
|
||||||
("outcome-unknown-arm", rmp_serde::to_vec(&("inv-1", 1i32, (4i32, (CANARY,)))).unwrap()),
|
|
||||||
// A result with a fourth slot past the last declared one.
|
|
||||||
(
|
|
||||||
"result-extra-slot",
|
|
||||||
rmp_serde::to_vec(&("inv-1", 1i32, (0i32, ("working",)), CANARY)).unwrap(),
|
|
||||||
),
|
|
||||||
// Each domain refusal is a tuple of real values with one slot out of domain.
|
|
||||||
// A result at seq 0.
|
|
||||||
("result-seq-zero", rmp_serde::to_vec(&("inv-1", 0i32, &pending)).unwrap()),
|
|
||||||
// A surface at version -1.
|
|
||||||
(
|
|
||||||
"surface-version-negative",
|
|
||||||
rmp_serde::to_vec(&("provider.a", "main", -1i64, CANARY, &root, unit)).unwrap(),
|
|
||||||
),
|
|
||||||
// A surface whose label holds a dot, so its key would be ambiguous.
|
|
||||||
(
|
|
||||||
"surface-label-dotted",
|
|
||||||
rmp_serde::to_vec(&("provider.a", "b.c", 1i64, CANARY, &root, unit)).unwrap(),
|
|
||||||
),
|
|
||||||
// An asset whose width is negative.
|
|
||||||
(
|
|
||||||
"asset-extent-negative",
|
|
||||||
rmp_serde::to_vec(&("provider.a", "icons", 1i64, [("gear", "image/png", CANARY, -5i32, 32i32)])).unwrap(),
|
|
||||||
),
|
|
||||||
// A colour channel past the u8 leaf.
|
|
||||||
("rgba-channel-out-of-range", rmp_serde::to_vec(&(256i32, 0i32, 0i32, 255i32)).unwrap()),
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn refusal_cases() {
|
|
||||||
let payloads: std::collections::BTreeMap<_, _> = refusal_payloads().into_iter().collect();
|
|
||||||
let committed = |name: &str| golden::check(&goldens_dir(), &format!("{name}.bin"), &payloads[name]);
|
|
||||||
|
|
||||||
// Stored under their key, each is refused naming the kind and the key, never a value.
|
|
||||||
let cases: [(&str, &str, &str); 7] = [
|
|
||||||
("result-thing1-flat", "gamecult.thing.command_result", "thing:result:inv-1.1"),
|
|
||||||
("node-unknown-arm", "gamecult.thing.surface", "thing:surface:provider.a.main"),
|
|
||||||
("outcome-unknown-arm", "gamecult.thing.command_result", "thing:result:inv-1.1"),
|
|
||||||
("result-seq-zero", "gamecult.thing.command_result", "thing:result:inv-1.0"),
|
|
||||||
("surface-version-negative", "gamecult.thing.surface", "thing:surface:provider.a.main"),
|
|
||||||
("surface-label-dotted", "gamecult.thing.surface", "thing:surface:provider.a.b.c"),
|
|
||||||
("asset-extent-negative", "gamecult.thing.asset_catalog", "thing:asset_catalog:provider.a.icons"),
|
|
||||||
];
|
|
||||||
for (name, kind, key) in cases {
|
|
||||||
let mut cache = CultCache::new();
|
|
||||||
ThingContract.register_entries(&mut cache).unwrap();
|
|
||||||
let bytes = committed(name);
|
|
||||||
let error = match kind {
|
|
||||||
"gamecult.thing.surface" => {
|
|
||||||
cache.put_envelope::<SurfaceDocument>(envelope::<SurfaceDocument>(key, bytes)).unwrap_err()
|
|
||||||
}
|
|
||||||
"gamecult.thing.asset_catalog" => {
|
|
||||||
cache.put_envelope::<AssetCatalog>(envelope::<AssetCatalog>(key, bytes)).unwrap_err()
|
|
||||||
}
|
|
||||||
_ => cache.put_envelope::<CommandResult>(envelope::<CommandResult>(key, bytes)).unwrap_err(),
|
|
||||||
};
|
|
||||||
let message = format!("{error:#}");
|
|
||||||
assert!(message.contains(kind), "{name}: the error names the kind: {message}");
|
|
||||||
assert!(message.contains(key), "{name}: the error names the record key: {message}");
|
|
||||||
assert!(!message.contains(CANARY), "{name}: the error echoed a value: {message}");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Decoded directly, the refusal names the union and the arm key, and never the payload.
|
|
||||||
for (name, union, key) in [("node-unknown-arm", "Node", "14"), ("outcome-unknown-arm", "Outcome", "4")] {
|
|
||||||
let bytes = committed(name);
|
|
||||||
let message = if union == "Node" {
|
|
||||||
rmp_serde::from_slice::<SurfaceDocument>(&bytes).unwrap_err().to_string()
|
|
||||||
} else {
|
|
||||||
rmp_serde::from_slice::<CommandResult>(&bytes).unwrap_err().to_string()
|
|
||||||
};
|
|
||||||
assert!(message.contains(union) && message.contains(key), "{name}: {message}");
|
|
||||||
assert!(!message.contains(CANARY), "{name}: {message}");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Decoded directly, a domain refusal names the domain and never the payload.
|
|
||||||
for (name, domain) in [
|
|
||||||
("result-seq-zero", "Seq"),
|
|
||||||
("surface-version-negative", "Version"),
|
|
||||||
("surface-label-dotted", "Segment"),
|
|
||||||
("asset-extent-negative", "Count"),
|
|
||||||
] {
|
|
||||||
let bytes = committed(name);
|
|
||||||
let message = match name {
|
|
||||||
"result-seq-zero" => rmp_serde::from_slice::<CommandResult>(&bytes).unwrap_err().to_string(),
|
|
||||||
"asset-extent-negative" => rmp_serde::from_slice::<AssetCatalog>(&bytes).unwrap_err().to_string(),
|
|
||||||
_ => rmp_serde::from_slice::<SurfaceDocument>(&bytes).unwrap_err().to_string(),
|
|
||||||
};
|
|
||||||
assert!(message.contains(domain), "{name}: {message}");
|
|
||||||
assert!(!message.contains(CANARY), "{name}: {message}");
|
|
||||||
}
|
|
||||||
|
|
||||||
// The u8 leaf refuses a channel past 255 when decoded as an Rgba.
|
|
||||||
let rgba = rmp_serde::from_slice::<Rgba>(&committed("rgba-channel-out-of-range")).unwrap_err();
|
|
||||||
assert!(!rgba.to_string().contains(CANARY));
|
|
||||||
|
|
||||||
// An extra trailing slot is read (CultLib's extra-trailing-slots ruling: read, never written
|
|
||||||
// back). Whether a missing slot is refused is CultLib's rule, so no golden asserts it.
|
|
||||||
let mut answered = invocation();
|
|
||||||
answered.invocation_id = "inv-1".into();
|
|
||||||
let extra: CommandResult = rmp_serde::from_slice(&committed("result-extra-slot")).unwrap();
|
|
||||||
assert_eq!(extra, CommandResult::pending(&answered, seq(1), "working"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn deep_tree() {
|
|
||||||
// A 64-deep Box chain.
|
|
||||||
let mut chain = text("leaf", "bottom");
|
|
||||||
for depth in (0..64).rev() {
|
|
||||||
chain = boxed(&format!("deep-{depth}"), vec![chain]);
|
|
||||||
}
|
|
||||||
let deep = SurfaceDocument {
|
|
||||||
provider_id: ProviderId::new("provider.a"),
|
|
||||||
label: seg("deep"),
|
|
||||||
version: ver(1),
|
|
||||||
title: "deep".into(),
|
|
||||||
root: chain,
|
|
||||||
commands: vec![],
|
|
||||||
};
|
|
||||||
// A surface of 1,000 nodes: the root, 998 texts and one box.
|
|
||||||
let mut wide_children: Vec<Node> = (0..998).map(|index| text(&format!("t{index}"), "x")).collect();
|
|
||||||
wide_children.push(boxed("tail", vec![]));
|
|
||||||
let wide = SurfaceDocument {
|
|
||||||
provider_id: ProviderId::new("provider.a"),
|
|
||||||
label: seg("wide"),
|
|
||||||
version: ver(1),
|
|
||||||
title: "wide".into(),
|
|
||||||
root: boxed("root", wide_children),
|
|
||||||
commands: vec![],
|
|
||||||
};
|
|
||||||
|
|
||||||
let path = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("deep-tree.cc");
|
|
||||||
{
|
|
||||||
let mut cache = store::create(&path);
|
|
||||||
store::put_pinned(&mut cache, &deep.record_key(), &deep);
|
|
||||||
store::put_pinned(&mut cache, &wide.record_key(), &wide);
|
|
||||||
}
|
|
||||||
let cache = store::open(&path);
|
|
||||||
assert_eq!(cache.get::<SurfaceDocument>(&deep.record_key()).unwrap(), Some(deep));
|
|
||||||
assert_eq!(cache.get::<SurfaceDocument>(&wide.record_key()).unwrap(), Some(wide));
|
|
||||||
}
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
* -text
|
|
||||||
|
|
@ -1,47 +0,0 @@
|
||||||
# thing-contract goldens
|
|
||||||
|
|
||||||
Written only by `crates/thing-contract/tests/goldens.rs`, with `THING_BLESS=1` set on that test.
|
|
||||||
Every other run compares byte for byte. The TypeScript and C# packages and core decode these files
|
|
||||||
and are held to the answers below; none of them writes one.
|
|
||||||
|
|
||||||
Each `.bin` is the payload of one record: the positional slot array of its kind, as MessagePack.
|
|
||||||
A union value is `[armKey, [armSlots...]]`; a unit arm is `[key, []]`. An optional member is nil
|
|
||||||
when absent. Arm keys are fixed for v1.
|
|
||||||
|
|
||||||
## Values (decode to the constructed value, re-encode to the same bytes)
|
|
||||||
|
|
||||||
| File | Kind | Decodes to |
|
|
||||||
|---|---|---|
|
|
||||||
| `surface-all-arms.bin` | `gamecult.thing.surface.v1` | One surface with 13 of the 14 node arms (Box 0, Text 1, Image 2, Button 3, Toggle 4, Slider 5, TextInput 6 as both input kinds, Text 0 and Number 1, Select 7, Repeat 8, Overlay 9, Plot 10, Embed 11, Use 12; Slot 13 is in `composition-all-params`, a body being where a slot stands), a Box chain four levels deep, every text, number and bool source arm, every Format arm, both state sources, both member steps, every dimension and colour arm, and two declared commands |
|
|
||||||
| `composition-all-params.bin` | `gamecult.thing.composition.v1` | A composition with one parameter of each of the 7 kinds, whose body uses a composition with one argument of each of the 7 argument arms and places the body slot (Slot 13) last in its root's children |
|
|
||||||
| `invocation-all-inputs.bin` | `gamecult.thing.command_invocation.v1` | An invocation with a payload record of bin bytes and one captured input of each of the 4 input arms, source `go-button` and items `[outer, inner]` |
|
|
||||||
| `result-pending.bin` | `gamecult.thing.command_result.v1` | Outcome Pending, seq 1 |
|
|
||||||
| `result-completed.bin` | same | Outcome Completed with source version 8, drafts cleared, no effect |
|
|
||||||
| `result-completed-open-surface.bin` | same | Completed with no source version and the OpenSurface effect |
|
|
||||||
| `result-completed-open-external.bin` | same | Completed with the OpenExternal effect and a resume command |
|
|
||||||
| `result-denied.bin` | same | Denied naming a node |
|
|
||||||
| `result-denied-no-node.bin` | same | Denied with a nil node |
|
|
||||||
| `result-failed.bin` | same | Failed |
|
|
||||||
| `asset-catalog.bin` | `gamecult.thing.asset_catalog.v1` | Two assets |
|
|
||||||
|
|
||||||
## Refusals and tolerance
|
|
||||||
|
|
||||||
| File | Payload | Expected |
|
|
||||||
|---|---|---|
|
|
||||||
| `result-thing1-flat.bin` | a MessagePack map with named members, the shape a Thing 1 provider wrote for a command result | refused when stored as a command result; the error names the kind and the record key and never a value |
|
|
||||||
| `node-unknown-arm.bin` | a surface whose root node has arm key 14, which Node does not declare | refused; the error names the kind and the record key, and decoded directly it names the union Node and the key 14, and never a value |
|
|
||||||
| `outcome-unknown-arm.bin` | a result whose outcome has arm key 4, which Outcome does not declare | refused in the same way, naming the union Outcome and the key 4 |
|
|
||||||
| `result-extra-slot.bin` | a Pending result with a fourth slot past the last one declared | read: it decodes to the Pending result with seq 1 (CultLib's extra-trailing-slots ruling: read, never written back) |
|
|
||||||
| `result-seq-zero.bin` | a result whose seq slot is 0 | refused; the error names the kind and the record key, decoded directly it names Seq, and never a value |
|
|
||||||
| `surface-version-negative.bin` | a surface whose version slot is -1 | refused in the same way, naming Version |
|
|
||||||
| `surface-label-dotted.bin` | a surface whose label is `b.c` | refused in the same way, naming Segment: a label holds no dot, so a record key splits at its last dot |
|
|
||||||
| `asset-extent-negative.bin` | an asset catalog whose first asset has width -5 | refused in the same way, naming Count |
|
|
||||||
| `rgba-channel-out-of-range.bin` | the Rgba slot array `[256, 0, 0, 255]` | refused when decoded as an Rgba: a channel is a byte, 0 to 255 |
|
|
||||||
|
|
||||||
Domain refusals are the contract's rule, which the TypeScript and C# packages mirror: each is held to refuse these files, without the leaf set a Rust `u8` or a checked newtype has.
|
|
||||||
|
|
||||||
## The nil vector
|
|
||||||
|
|
||||||
`nil-positions.tsv` is written only by `crates/thing-contract/tests/nil_positions.rs` (`THING_BLESS=1`). For every element inside an array, at every depth, of each value golden above (the eleven `.bin` files from `surface-all-arms` to `asset-catalog`), the test replaces that element with nil (`0xC0`) and decodes the whole payload with the Rust decode door, `rmp_serde::from_slice` into the golden's kind. A row is `golden`, `path` (dotted array indices from the root, e.g. `3.0.1`), the element's byte `start` and `end` in the golden, and `ACCEPT` or `REFUSE`. An accepted variant re-encodes to the spliced bytes. Maps are not walked.
|
|
||||||
|
|
||||||
A slot is required exactly when its Rust type is not optional, so `REFUSE` rows are the required slots and `ACCEPT` rows the optional ones. The Rust decode door decides every row; the TypeScript and C# packages keep no list of required slots and are held to every row.
|
|
||||||
Binary file not shown.
|
|
@ -1 +0,0 @@
|
||||||
”ªprovider.a¥icons‘•¤gear©image/png¯CANARY-7f3a91c2û
|
|
||||||
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large
Load diff
|
|
@ -1 +0,0 @@
|
||||||
–ªprovider.a¤main¯CANARY-7f3a91c2’‘¯CANARY-7f3a91c2<63>
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
“¥inv-1’‘¯CANARY-7f3a91c2
|
|
||||||
Binary file not shown.
Binary file not shown.
|
|
@ -1 +0,0 @@
|
||||||
“Ù$3f2b8c1e-5d44-4a6b-9a07-1c2d3e4f5a6b’“ÃÀ
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
“Ù$3f2b8c1e-5d44-4a6b-9a07-1c2d3e4f5a6b’’«not allowedÀ
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
“Ù$3f2b8c1e-5d44-4a6b-9a07-1c2d3e4f5a6b’’©not yours¢go
|
|
||||||
Binary file not shown.
|
|
@ -1 +0,0 @@
|
||||||
“Ù$3f2b8c1e-5d44-4a6b-9a07-1c2d3e4f5a6b’‘¥broke
|
|
||||||
Binary file not shown.
Binary file not shown.
|
|
@ -1 +0,0 @@
|
||||||
<EFBFBD>§receipt†©commandId¥inv-1§command¢go¥state©completed§message¯CANARY-7f3a91c2sourceVersion«issuedAtUtc´2026-01-01T00:00:00Z
|
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
|
|
@ -1,132 +0,0 @@
|
||||||
//! The nil vector: for every element of every array of every value golden, the golden with that
|
|
||||||
//! element replaced by nil, and whether the Rust decode door accepts it. A slot is required
|
|
||||||
//! exactly when its Rust type is not optional, so the rows are the required-slot set; the C# and
|
|
||||||
//! TypeScript packages hold no list of their own and are held to every row.
|
|
||||||
//! `THING_BLESS=1` rewrites `goldens/nil-positions.tsv`; any other run compares.
|
|
||||||
|
|
||||||
use std::fmt::Debug;
|
|
||||||
use std::path::PathBuf;
|
|
||||||
|
|
||||||
use serde::Serialize;
|
|
||||||
use serde::de::DeserializeOwned;
|
|
||||||
use thing_contract::*;
|
|
||||||
use thing_testkit::golden;
|
|
||||||
|
|
||||||
/// One MessagePack value's byte span; `kids` is set for arrays only (maps are never walked).
|
|
||||||
struct Span {
|
|
||||||
start: usize,
|
|
||||||
end: usize,
|
|
||||||
kids: Option<Vec<Span>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn be(bytes: &[u8], at: usize, width: usize) -> usize {
|
|
||||||
bytes[at..at + width].iter().fold(0, |acc, byte| acc << 8 | *byte as usize)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn collection(bytes: &[u8], start: usize, mut at: usize, count: usize, is_array: bool) -> Span {
|
|
||||||
let mut kids = Vec::new();
|
|
||||||
for _ in 0..count {
|
|
||||||
let kid = item(bytes, at);
|
|
||||||
at = kid.end;
|
|
||||||
kids.push(kid);
|
|
||||||
}
|
|
||||||
Span { start, end: at, kids: is_array.then_some(kids) }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn item(bytes: &[u8], at: usize) -> Span {
|
|
||||||
let tag = bytes[at];
|
|
||||||
let flat = |len: usize| Span { start: at, end: at + len, kids: None };
|
|
||||||
match tag {
|
|
||||||
0x00..=0x7f | 0xe0..=0xff | 0xc0 | 0xc2 | 0xc3 => flat(1),
|
|
||||||
0x80..=0x8f => collection(bytes, at, at + 1, (tag & 0x0f) as usize * 2, false),
|
|
||||||
0x90..=0x9f => collection(bytes, at, at + 1, (tag & 0x0f) as usize, true),
|
|
||||||
0xa0..=0xbf => flat(1 + (tag & 0x1f) as usize),
|
|
||||||
0xc4 | 0xd9 => flat(2 + be(bytes, at + 1, 1)),
|
|
||||||
0xc5 | 0xda => flat(3 + be(bytes, at + 1, 2)),
|
|
||||||
0xc6 | 0xdb => flat(5 + be(bytes, at + 1, 4)),
|
|
||||||
0xca => flat(5),
|
|
||||||
0xcb => flat(9),
|
|
||||||
0xcc | 0xd0 => flat(2),
|
|
||||||
0xcd | 0xd1 => flat(3),
|
|
||||||
0xce | 0xd2 => flat(5),
|
|
||||||
0xcf | 0xd3 => flat(9),
|
|
||||||
0xdc => collection(bytes, at, at + 3, be(bytes, at + 1, 2), true),
|
|
||||||
0xdd => collection(bytes, at, at + 5, be(bytes, at + 1, 4), true),
|
|
||||||
0xde => collection(bytes, at, at + 3, be(bytes, at + 1, 2) * 2, false),
|
|
||||||
0xdf => collection(bytes, at, at + 5, be(bytes, at + 1, 4) * 2, false),
|
|
||||||
0xd4 => flat(3),
|
|
||||||
0xd5 => flat(4),
|
|
||||||
0xd6 => flat(6),
|
|
||||||
0xd7 => flat(10),
|
|
||||||
0xd8 => flat(18),
|
|
||||||
0xc7 => flat(3 + be(bytes, at + 1, 1)),
|
|
||||||
0xc8 => flat(4 + be(bytes, at + 1, 2)),
|
|
||||||
0xc9 => flat(6 + be(bytes, at + 1, 4)),
|
|
||||||
_ => panic!("unsupported tag {tag:#x} at {at}"),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every element inside an array, at every depth, in walk order, with its dotted index path.
|
|
||||||
fn elements(span: &Span, prefix: &str, out: &mut Vec<(String, usize, usize)>) {
|
|
||||||
for (index, kid) in span.kids.iter().flatten().enumerate() {
|
|
||||||
let path = if prefix.is_empty() { index.to_string() } else { format!("{prefix}.{index}") };
|
|
||||||
out.push((path.clone(), kid.start, kid.end));
|
|
||||||
elements(kid, &path, out);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The rows of one golden: nil spliced over each element, decoded as `T`. An accepted variant
|
|
||||||
/// must re-encode to the spliced bytes.
|
|
||||||
fn rows<T: DeserializeOwned + Serialize + Debug>(file: &str, out: &mut String) -> (usize, usize) {
|
|
||||||
let bytes = golden::read(&goldens_dir(), &format!("{file}.bin"));
|
|
||||||
let mut found = Vec::new();
|
|
||||||
elements(&item(&bytes, 0), "", &mut found);
|
|
||||||
let (mut accepted, mut refused) = (0, 0);
|
|
||||||
for (path, start, end) in found {
|
|
||||||
let mut spliced = bytes[..start].to_vec();
|
|
||||||
spliced.push(0xc0);
|
|
||||||
spliced.extend_from_slice(&bytes[end..]);
|
|
||||||
let verdict = match rmp_serde::from_slice::<T>(&spliced) {
|
|
||||||
Ok(value) => {
|
|
||||||
assert_eq!(rmp_serde::to_vec(&value).unwrap(), spliced, "{file} {path}: an accepted nil must re-encode to the spliced bytes");
|
|
||||||
accepted += 1;
|
|
||||||
"ACCEPT"
|
|
||||||
}
|
|
||||||
Err(_) => {
|
|
||||||
refused += 1;
|
|
||||||
"REFUSE"
|
|
||||||
}
|
|
||||||
};
|
|
||||||
out.push_str(&format!("{file}\t{path}\t{start}\t{end}\t{verdict}\n"));
|
|
||||||
}
|
|
||||||
(accepted, refused)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn nil_positions_match() {
|
|
||||||
let mut table = String::new();
|
|
||||||
let mut totals = Vec::new();
|
|
||||||
totals.push(("surface-all-arms", rows::<SurfaceDocument>("surface-all-arms", &mut table)));
|
|
||||||
totals.push(("composition-all-params", rows::<CompositionDocument>("composition-all-params", &mut table)));
|
|
||||||
totals.push(("invocation-all-inputs", rows::<CommandInvocation>("invocation-all-inputs", &mut table)));
|
|
||||||
for file in [
|
|
||||||
"result-pending",
|
|
||||||
"result-completed",
|
|
||||||
"result-completed-open-surface",
|
|
||||||
"result-completed-open-external",
|
|
||||||
"result-denied",
|
|
||||||
"result-denied-no-node",
|
|
||||||
"result-failed",
|
|
||||||
] {
|
|
||||||
totals.push((file, rows::<CommandResult>(file, &mut table)));
|
|
||||||
}
|
|
||||||
totals.push(("asset-catalog", rows::<AssetCatalog>("asset-catalog", &mut table)));
|
|
||||||
for (file, (accepted, refused)) in &totals {
|
|
||||||
println!("NILTOTAL {file} accept={accepted} refuse={refused}");
|
|
||||||
}
|
|
||||||
golden::check(&goldens_dir(), "nil-positions.tsv", table.as_bytes());
|
|
||||||
}
|
|
||||||
|
|
||||||
fn goldens_dir() -> PathBuf {
|
|
||||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
|
|
||||||
}
|
|
||||||
|
|
@ -1,224 +0,0 @@
|
||||||
use thing_testkit::build::*;
|
|
||||||
use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry, decode_payload};
|
|
||||||
use serde::Deserialize;
|
|
||||||
use serde::de::IntoDeserializer;
|
|
||||||
use serde::de::value::{Error as ValueError, I32Deserializer, I64Deserializer, StringDeserializer};
|
|
||||||
use thing_contract::*;
|
|
||||||
|
|
||||||
const CANARY: &str = "CANARY-9d41c7e0";
|
|
||||||
|
|
||||||
fn other_invocation() -> CommandInvocation {
|
|
||||||
let mut other = invocation();
|
|
||||||
other.invocation_id = "an-invocation-no-constructor-can-guess".into();
|
|
||||||
other
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn result_copies_invocation_id() {
|
|
||||||
let invocation = other_invocation();
|
|
||||||
let built = [
|
|
||||||
CommandResult::pending(&invocation, seq(1), "m"),
|
|
||||||
CommandResult::completed(&invocation, seq(2), None, false, None),
|
|
||||||
CommandResult::denied(&invocation, seq(3), "r", None),
|
|
||||||
CommandResult::failed(&invocation, seq(4), "r"),
|
|
||||||
];
|
|
||||||
for (index, result) in built.iter().enumerate() {
|
|
||||||
assert_eq!(result.invocation_id(), "an-invocation-no-constructor-can-guess");
|
|
||||||
assert_eq!(result.seq().get(), index as i32 + 1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn each_constructor_builds_its_outcome_arm() {
|
|
||||||
let invocation = other_invocation();
|
|
||||||
let node = Some(nid("go"));
|
|
||||||
assert!(matches!(
|
|
||||||
CommandResult::pending(&invocation, seq(1), "wait").outcome(),
|
|
||||||
Outcome::Pending(PendingOutcome { message }) if message == "wait"
|
|
||||||
));
|
|
||||||
let effect = Effect::OpenSurface(OpenSurfaceEffect { key: "k".into() });
|
|
||||||
assert!(matches!(
|
|
||||||
CommandResult::completed(&invocation, seq(1), Some(ver(5)), true, Some(effect.clone())).outcome(),
|
|
||||||
Outcome::Completed(CompletedOutcome { source_version: Some(v), clear_drafts: true, effect: Some(e) })
|
|
||||||
if v.get() == 5 && *e == effect
|
|
||||||
));
|
|
||||||
assert!(matches!(
|
|
||||||
CommandResult::completed(&invocation, seq(1), None, false, None).outcome(),
|
|
||||||
Outcome::Completed(CompletedOutcome { source_version: None, clear_drafts: false, effect: None })
|
|
||||||
));
|
|
||||||
assert!(matches!(
|
|
||||||
CommandResult::denied(&invocation, seq(1), "no", node.clone()).outcome(),
|
|
||||||
Outcome::Denied(DeniedOutcome { reason, node: n }) if reason == "no" && *n == node
|
|
||||||
));
|
|
||||||
assert!(matches!(
|
|
||||||
CommandResult::failed(&invocation, seq(1), "broke").outcome(),
|
|
||||||
Outcome::Failed(FailedOutcome { reason }) if reason == "broke"
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn surface(provider: &str, label: &str) -> SurfaceDocument {
|
|
||||||
SurfaceDocument {
|
|
||||||
provider_id: ProviderId::new(provider),
|
|
||||||
label: seg(label),
|
|
||||||
version: ver(1),
|
|
||||||
title: String::new(),
|
|
||||||
root: boxed("r", vec![]),
|
|
||||||
commands: vec![],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn composition(publisher: &str, name: &str, version: i64) -> CompositionDocument {
|
|
||||||
CompositionDocument {
|
|
||||||
publisher: publisher.into(),
|
|
||||||
name: seg(name),
|
|
||||||
version: ver(version),
|
|
||||||
params: vec![],
|
|
||||||
body: boxed("r", vec![]),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn catalog(provider: &str, id: &str) -> AssetCatalog {
|
|
||||||
AssetCatalog { provider_id: ProviderId::new(provider), catalog_id: seg(id), version: ver(1), assets: vec![] }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn record_keys_are_built_from_the_fields() {
|
|
||||||
let invocation = other_invocation();
|
|
||||||
assert_eq!(invocation.record_key(), "thing:invocation:an-invocation-no-constructor-can-guess");
|
|
||||||
assert_eq!(
|
|
||||||
CommandResult::failed(&invocation, seq(3), "r").record_key(),
|
|
||||||
"thing:result:an-invocation-no-constructor-can-guess.3"
|
|
||||||
);
|
|
||||||
assert_eq!(surface("p", "main").record_key(), "thing:surface:p.main");
|
|
||||||
assert_eq!(composition("pub", "card", 2).record_key(), "thing:composition:pub.card.v2");
|
|
||||||
assert_eq!(catalog("p", "icons").record_key(), "thing:asset_catalog:p.icons");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn record_keys_injective() {
|
|
||||||
// The pair the old keys collided on: a dotted provider with a plain label, and a plain
|
|
||||||
// provider with a dotted label. The second no longer exists.
|
|
||||||
assert_eq!(surface("a.b", "c").record_key(), "thing:surface:a.b.c");
|
|
||||||
assert!(Segment::new("b.c").is_err());
|
|
||||||
assert_ne!(surface("a", "c").record_key(), surface("a.b", "c").record_key());
|
|
||||||
assert_ne!(surface("a.b", "c").record_key(), surface("a", "bc").record_key());
|
|
||||||
|
|
||||||
// A composition splits at its last two dots: publisher, name, then the version.
|
|
||||||
assert_eq!(composition("a.b", "c", 1).record_key(), "thing:composition:a.b.c.v1");
|
|
||||||
assert_ne!(composition("a.b", "c", 1).record_key(), composition("a", "bc", 1).record_key());
|
|
||||||
assert_ne!(composition("a", "c", 1).record_key(), composition("a", "c", 11).record_key());
|
|
||||||
assert_ne!(composition("a", "c", 1).record_key(), composition("a", "c", 0).record_key());
|
|
||||||
|
|
||||||
// A catalog likewise, and under the asset_catalog prefix.
|
|
||||||
assert_eq!(catalog("a.b", "c").record_key(), "thing:asset_catalog:a.b.c");
|
|
||||||
assert_ne!(catalog("a.b", "c").record_key(), catalog("a", "bc").record_key());
|
|
||||||
|
|
||||||
// A result splits at its last dot, and the seq is digits.
|
|
||||||
let mut inv = invocation();
|
|
||||||
inv.invocation_id = "x.1".into();
|
|
||||||
let first = CommandResult::failed(&inv, seq(2), "r").record_key();
|
|
||||||
inv.invocation_id = "x".into();
|
|
||||||
let second = CommandResult::failed(&inv, seq(12), "r").record_key();
|
|
||||||
assert_eq!(first, "thing:result:x.1.2");
|
|
||||||
assert_eq!(second, "thing:result:x.12");
|
|
||||||
assert_ne!(first, second);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn domain_newtypes_refuse_out_of_domain() {
|
|
||||||
// new, the one door.
|
|
||||||
for bad in [0, -1, i32::MIN] {
|
|
||||||
assert!(Seq::new(bad).is_err(), "Seq {bad}");
|
|
||||||
}
|
|
||||||
assert_eq!(Seq::new(1).unwrap(), Seq::FIRST);
|
|
||||||
assert_eq!(Seq::new(i32::MAX).unwrap().next(), Seq::new(i32::MAX).unwrap());
|
|
||||||
assert_eq!(Seq::FIRST.next().get(), 2);
|
|
||||||
assert!(Version::new(-1).is_err());
|
|
||||||
assert!(Version::new(i64::MIN).is_err());
|
|
||||||
assert_eq!(Version::new(0).unwrap().get(), 0);
|
|
||||||
assert!(Count::new(-1).is_err());
|
|
||||||
assert!(Count::new(i32::MIN).is_err());
|
|
||||||
assert_eq!(Count::new(0).unwrap().get(), 0);
|
|
||||||
assert_eq!(Count::new(7).unwrap().get(), 7);
|
|
||||||
assert!(Segment::new("").is_err());
|
|
||||||
assert!(Segment::new("a.b").is_err());
|
|
||||||
assert!(Segment::new(".").is_err());
|
|
||||||
assert_eq!(Segment::new("ab").unwrap().as_str(), "ab");
|
|
||||||
|
|
||||||
// serde, the other door: rmp_serde and serde's own IntoDeserializer.
|
|
||||||
for bad in [0, -1, i32::MIN] {
|
|
||||||
assert!(rmp_serde::from_slice::<Seq>(&rmp_serde::to_vec(&bad).unwrap()).is_err(), "Seq {bad}");
|
|
||||||
assert!(Seq::deserialize(I32Deserializer::<ValueError>::new(bad)).is_err());
|
|
||||||
assert!(Count::deserialize(I32Deserializer::<ValueError>::new(bad)).is_ok() == (bad >= 0));
|
|
||||||
}
|
|
||||||
assert_eq!(Seq::deserialize(I32Deserializer::<ValueError>::new(1)).unwrap(), Seq::FIRST);
|
|
||||||
assert!(rmp_serde::from_slice::<Version>(&rmp_serde::to_vec(&-1i64).unwrap()).is_err());
|
|
||||||
assert!(Version::deserialize(I64Deserializer::<ValueError>::new(-1)).is_err());
|
|
||||||
assert_eq!(Version::deserialize(I64Deserializer::<ValueError>::new(0)).unwrap().get(), 0);
|
|
||||||
assert!(rmp_serde::from_slice::<Count>(&rmp_serde::to_vec(&-1i32).unwrap()).is_err());
|
|
||||||
assert_eq!(Count::deserialize(I32Deserializer::<ValueError>::new(0)).unwrap().get(), 0);
|
|
||||||
for bad in ["", "a.b"] {
|
|
||||||
assert!(rmp_serde::from_slice::<Segment>(&rmp_serde::to_vec(bad).unwrap()).is_err(), "Segment {bad:?}");
|
|
||||||
let deserializer: StringDeserializer<ValueError> = bad.to_string().into_deserializer();
|
|
||||||
assert!(Segment::deserialize(deserializer).is_err());
|
|
||||||
}
|
|
||||||
let deserializer: StringDeserializer<ValueError> = "ab".to_string().into_deserializer();
|
|
||||||
assert_eq!(Segment::deserialize(deserializer).unwrap().as_str(), "ab");
|
|
||||||
|
|
||||||
// Each writes exactly the plain leaf, so the bytes are the leaf's.
|
|
||||||
assert_eq!(rmp_serde::to_vec(&seq(5)).unwrap(), rmp_serde::to_vec(&5i32).unwrap());
|
|
||||||
assert_eq!(rmp_serde::to_vec(&ver(5)).unwrap(), rmp_serde::to_vec(&5i64).unwrap());
|
|
||||||
assert_eq!(rmp_serde::to_vec(&count(5)).unwrap(), rmp_serde::to_vec(&5i32).unwrap());
|
|
||||||
assert_eq!(rmp_serde::to_vec(&seg("ab")).unwrap(), rmp_serde::to_vec("ab").unwrap());
|
|
||||||
|
|
||||||
// The error names the domain and its bound, never the value.
|
|
||||||
let message = Segment::new(format!("{CANARY}.x")).unwrap_err().to_string();
|
|
||||||
assert_eq!(message, "Segment must be free of '.'");
|
|
||||||
assert_eq!(Seq::new(-77).unwrap_err().to_string(), "Seq must be at least 1");
|
|
||||||
assert_eq!(Version::new(-77).unwrap_err().to_string(), "Version must be at least 0");
|
|
||||||
assert_eq!(Count::new(-77).unwrap_err().to_string(), "Count must be at least 0");
|
|
||||||
assert_eq!(Segment::new("").unwrap_err().to_string(), "Segment must be non-empty");
|
|
||||||
let error = Segment::new(format!("{CANARY}.x")).unwrap_err();
|
|
||||||
assert_eq!((error.domain(), error.bound()), ("Segment", "free of '.'"));
|
|
||||||
assert!(!format!("{error:?}").contains(CANARY));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The result payload `[id, seq, [0, [message]]]` with the seq slot spelled by the caller.
|
|
||||||
fn result_payload(seq_slot: i32) -> Vec<u8> {
|
|
||||||
let pending = Outcome::Pending(PendingOutcome { message: CANARY.into() });
|
|
||||||
rmp_serde::to_vec(&("inv-1", seq_slot, &pending)).unwrap()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn result_decode_door_holds_domain() {
|
|
||||||
// A seq the constructors cannot build is refused by every decode door.
|
|
||||||
for bad in [0, -1, i32::MIN] {
|
|
||||||
let payload = result_payload(bad);
|
|
||||||
let message = rmp_serde::from_slice::<CommandResult>(&payload).unwrap_err().to_string();
|
|
||||||
assert!(message.contains("Seq") && !message.contains(CANARY), "{message}");
|
|
||||||
|
|
||||||
let message = format!("{:#}", decode_payload::<CommandResult>(&payload).unwrap_err());
|
|
||||||
assert!(!message.contains(CANARY), "{message}");
|
|
||||||
|
|
||||||
let mut cache = CultCache::new();
|
|
||||||
ThingContract.register_entries(&mut cache).unwrap();
|
|
||||||
let key = format!("thing:result:inv-1.{bad}");
|
|
||||||
let envelope = CultCacheEnvelope {
|
|
||||||
key: key.clone(),
|
|
||||||
r#type: CommandResult::TYPE.into(),
|
|
||||||
payload,
|
|
||||||
stored_at: "2026-01-01T00:00:00Z".into(),
|
|
||||||
schema_id: Some(CommandResult::TYPE.into()),
|
|
||||||
};
|
|
||||||
let message = format!("{:#}", cache.put_envelope::<CommandResult>(envelope).unwrap_err());
|
|
||||||
assert!(message.contains("gamecult.thing.command_result") && message.contains(&key), "{message}");
|
|
||||||
assert!(!message.contains(CANARY), "{message}");
|
|
||||||
}
|
|
||||||
|
|
||||||
// The boundary decodes, and equals what the constructor builds.
|
|
||||||
let mut answered = invocation();
|
|
||||||
answered.invocation_id = "inv-1".into();
|
|
||||||
let expected = CommandResult::pending(&answered, Seq::FIRST, CANARY);
|
|
||||||
assert_eq!(rmp_serde::from_slice::<CommandResult>(&result_payload(1)).unwrap(), expected);
|
|
||||||
assert_eq!(decode_payload::<CommandResult>(&result_payload(1)).unwrap(), expected);
|
|
||||||
}
|
|
||||||
|
|
@ -1,20 +0,0 @@
|
||||||
[package]
|
|
||||||
name = "thing-core"
|
|
||||||
version = "0.1.0"
|
|
||||||
edition = "2024"
|
|
||||||
license = "MIT"
|
|
||||||
publish = false
|
|
||||||
|
|
||||||
# Normal dependencies are thing-contract, stacker, taffy and the three Unicode tables of the Cells
|
|
||||||
# text engine (unicode-width, unicode-segmentation, unicode-linebreak): layout and terminal text
|
|
||||||
# are thing-core's job, and no Taffy type is in its public API.
|
|
||||||
[dependencies]
|
|
||||||
thing-contract = { path = "../thing-contract" }
|
|
||||||
stacker = "0.1.25"
|
|
||||||
taffy.workspace = true
|
|
||||||
unicode-width.workspace = true
|
|
||||||
unicode-segmentation.workspace = true
|
|
||||||
unicode-linebreak.workspace = true
|
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
thing-testkit = { path = "../thing-testkit" }
|
|
||||||
|
|
@ -1,172 +0,0 @@
|
||||||
//! Format: total and locale-free. Each function takes the value the site read and returns the
|
|
||||||
//! text, or the reason the value does not fit (a detail that never carries the value).
|
|
||||||
|
|
||||||
use thing_contract::{AffixFormat, NumberFormat, is_timestamp_text};
|
|
||||||
|
|
||||||
/// Fixed-point text of `n` at `format.precision`, scaled by 100 for a percent, with the percent
|
|
||||||
/// sign and the unit. Non-finite numbers print as NaN, inf, -inf; negative zero prints as zero.
|
|
||||||
pub fn number(n: f64, format: &NumberFormat) -> String {
|
|
||||||
let scaled = if format.percent { n * 100.0 } else { n };
|
|
||||||
let mut text = if scaled.is_nan() {
|
|
||||||
"NaN".to_string()
|
|
||||||
} else if scaled.is_infinite() {
|
|
||||||
if scaled > 0.0 { "inf" } else { "-inf" }.to_string()
|
|
||||||
} else {
|
|
||||||
format!("{scaled:.*}", format.precision.get() as usize)
|
|
||||||
};
|
|
||||||
if text.starts_with('-') && text[1..].bytes().all(|byte| byte == b'0' || byte == b'.') {
|
|
||||||
text.remove(0);
|
|
||||||
}
|
|
||||||
if format.percent {
|
|
||||||
text.push('%');
|
|
||||||
}
|
|
||||||
if let Some(unit) = &format.unit {
|
|
||||||
text.push(' ');
|
|
||||||
text.push_str(unit);
|
|
||||||
}
|
|
||||||
text
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Seconds rounded half away from zero, printed by the largest unit present with the later
|
|
||||||
/// units at two digits: `5s`, `1m 05s`, `1h 00m 05s`, `1d 01h 00m 00s`, a leading `-` when negative.
|
|
||||||
pub fn duration(seconds: f64) -> Result<String, &'static str> {
|
|
||||||
if !seconds.is_finite() {
|
|
||||||
return Err("a duration is not finite");
|
|
||||||
}
|
|
||||||
let total = seconds.round() as i128;
|
|
||||||
let t = total.unsigned_abs();
|
|
||||||
let (days, hours, minutes, secs) = (t / 86_400, t % 86_400 / 3_600, t % 3_600 / 60, t % 60);
|
|
||||||
let body = if days > 0 {
|
|
||||||
format!("{days}d {hours:02}h {minutes:02}m {secs:02}s")
|
|
||||||
} else if hours > 0 {
|
|
||||||
format!("{hours}h {minutes:02}m {secs:02}s")
|
|
||||||
} else if minutes > 0 {
|
|
||||||
format!("{minutes}m {secs:02}s")
|
|
||||||
} else {
|
|
||||||
format!("{secs}s")
|
|
||||||
};
|
|
||||||
Ok(if total < 0 { format!("-{body}") } else { body })
|
|
||||||
}
|
|
||||||
|
|
||||||
const FIRST_SECOND: i128 = -62_135_596_800; // 0001-01-01T00:00:00Z
|
|
||||||
const LAST_SECOND: i128 = 253_402_300_799; // 9999-12-31T23:59:59Z
|
|
||||||
|
|
||||||
/// Unix seconds, floored, as `YYYY-MM-DDTHH:MM:SSZ` in UTC, years 0001 to 9999.
|
|
||||||
pub fn timestamp(seconds: f64) -> Result<String, &'static str> {
|
|
||||||
if !seconds.is_finite() {
|
|
||||||
return Err("a timestamp is not finite");
|
|
||||||
}
|
|
||||||
let floored = seconds.floor() as i128;
|
|
||||||
if !(FIRST_SECOND..=LAST_SECOND).contains(&floored) {
|
|
||||||
return Err("a timestamp is outside years 0001 to 9999");
|
|
||||||
}
|
|
||||||
let (days, rest) = (floored.div_euclid(86_400), floored.rem_euclid(86_400));
|
|
||||||
let (year, month, day) = civil(days as i64);
|
|
||||||
Ok(format!("{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z", rest / 3_600, rest % 3_600 / 60, rest % 60))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Days since 1970-01-01 as a proleptic Gregorian date.
|
|
||||||
fn civil(days: i64) -> (i64, i64, i64) {
|
|
||||||
let z = days + 719_468;
|
|
||||||
let era = z.div_euclid(146_097);
|
|
||||||
let day_of_era = z.rem_euclid(146_097);
|
|
||||||
let year_of_era = (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
|
|
||||||
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
|
|
||||||
let month_index = (5 * day_of_year + 2) / 153;
|
|
||||||
let day = day_of_year - (153 * month_index + 2) / 5 + 1;
|
|
||||||
let month = if month_index < 10 { month_index + 3 } else { month_index - 9 };
|
|
||||||
(year_of_era + era * 400 + i64::from(month <= 2), month, day)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Text that is already a `stored_at` stamp, as written.
|
|
||||||
pub fn stamp(text: &str) -> Result<String, &'static str> {
|
|
||||||
if is_timestamp_text(text) { Ok(text.to_string()) } else { Err("the text is not a timestamp") }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn affix(text: &str, format: &AffixFormat) -> String {
|
|
||||||
format!("{}{text}{}", format.prefix, format.suffix)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use thing_contract::Count;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn fmt(precision: i32, percent: bool, unit: Option<&str>) -> NumberFormat {
|
|
||||||
NumberFormat { precision: Count::new(precision).unwrap(), percent, unit: unit.map(Into::into) }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn number_table() {
|
|
||||||
let table = [
|
|
||||||
(0.42, fmt(1, true, None), "42.0%"),
|
|
||||||
(3.14159, fmt(2, false, None), "3.14"),
|
|
||||||
(2.5, fmt(0, false, None), "2"),
|
|
||||||
(1234.5, fmt(1, false, Some("MB")), "1234.5 MB"),
|
|
||||||
(0.5, fmt(0, true, Some("of cap")), "50% of cap"),
|
|
||||||
(-0.0, fmt(1, false, None), "0.0"),
|
|
||||||
(-0.04, fmt(1, false, None), "0.0"),
|
|
||||||
(-1.25, fmt(1, false, None), "-1.2"),
|
|
||||||
(f64::NAN, fmt(2, true, None), "NaN%"),
|
|
||||||
(f64::INFINITY, fmt(2, false, Some("x")), "inf x"),
|
|
||||||
(f64::NEG_INFINITY, fmt(0, false, None), "-inf"),
|
|
||||||
];
|
|
||||||
for (n, format, expected) in table {
|
|
||||||
assert_eq!(number(n, &format), expected, "{n} {format:?}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn duration_table() {
|
|
||||||
let table = [
|
|
||||||
(0.0, "0s"),
|
|
||||||
(5.0, "5s"),
|
|
||||||
(59.4, "59s"),
|
|
||||||
(59.5, "1m 00s"),
|
|
||||||
(65.0, "1m 05s"),
|
|
||||||
(3605.0, "1h 00m 05s"),
|
|
||||||
(90_000.0, "1d 01h 00m 00s"),
|
|
||||||
(-65.0, "-1m 05s"),
|
|
||||||
(-0.4, "0s"),
|
|
||||||
(-0.5, "-1s"),
|
|
||||||
];
|
|
||||||
for (seconds, expected) in table {
|
|
||||||
assert_eq!(duration(seconds).unwrap(), expected, "{seconds}");
|
|
||||||
}
|
|
||||||
assert!(duration(f64::NAN).is_err() && duration(f64::INFINITY).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn timestamp_table() {
|
|
||||||
let table = [
|
|
||||||
(0.0, "1970-01-01T00:00:00Z"),
|
|
||||||
(0.9, "1970-01-01T00:00:00Z"),
|
|
||||||
(-0.1, "1969-12-31T23:59:59Z"),
|
|
||||||
(951_782_400.0, "2000-02-29T00:00:00Z"),
|
|
||||||
(1_767_225_600.0, "2026-01-01T00:00:00Z"),
|
|
||||||
(-62_135_596_800.0, "0001-01-01T00:00:00Z"),
|
|
||||||
(253_402_300_799.0, "9999-12-31T23:59:59Z"),
|
|
||||||
];
|
|
||||||
for (seconds, expected) in table {
|
|
||||||
assert_eq!(timestamp(seconds).unwrap(), expected, "{seconds}");
|
|
||||||
}
|
|
||||||
assert!(timestamp(253_402_300_800.0).is_err());
|
|
||||||
assert!(timestamp(-62_135_596_801.0).is_err());
|
|
||||||
assert!(timestamp(f64::NAN).is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn stamp_text_is_printed_as_written() {
|
|
||||||
assert_eq!(stamp("2026-01-01T00:00:00Z").unwrap(), "2026-01-01T00:00:00Z");
|
|
||||||
assert_eq!(stamp("2026-01-01T02:00:00.5+02:00").unwrap(), "2026-01-01T02:00:00.5+02:00");
|
|
||||||
assert!(stamp("yesterday").is_err());
|
|
||||||
assert!(stamp("2026-01-01 00:00:00Z").is_err());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn affix_wraps_text() {
|
|
||||||
let format = AffixFormat { prefix: "[".into(), suffix: "]".into() };
|
|
||||||
assert_eq!(affix("ok", &format), "[ok]");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,346 +0,0 @@
|
||||||
//! Bind: a `ResolvedTree` and provider state become a `BoundTree`, the value of every source
|
|
||||||
//! site of every node, the instances of every Repeat and the typed faults between. The Binder is
|
|
||||||
//! handed trees and the changes the frame owner drained; it never drains, never decodes and keeps
|
|
||||||
//! no state value beside the port: a changed address is read again. The state interests it holds
|
|
||||||
//! are exactly the ones the bound trees read, held through the shared `Ledger`.
|
|
||||||
//!
|
|
||||||
//! A bound tree is a side table over the resolved document, not a second node tree.
|
|
||||||
|
|
||||||
mod format;
|
|
||||||
mod repeat;
|
|
||||||
mod walk;
|
|
||||||
|
|
||||||
use std::collections::{BTreeMap, HashMap, HashSet};
|
|
||||||
|
|
||||||
use thing_contract::{AssetEntry, NodeId, SelectOption};
|
|
||||||
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
use crate::port::{Address, Change, Interest, Ledger, StatePort};
|
|
||||||
use crate::resolve::{Limits, ResolvedTree};
|
|
||||||
use walk::{Unit, Walker};
|
|
||||||
|
|
||||||
/// Every source site a node can carry. Closed.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
|
||||||
pub enum Field {
|
|
||||||
Visible,
|
|
||||||
A11yLabel,
|
|
||||||
Content,
|
|
||||||
Alt,
|
|
||||||
Enabled,
|
|
||||||
Checked,
|
|
||||||
Value,
|
|
||||||
Placeholder,
|
|
||||||
Initial,
|
|
||||||
Selected,
|
|
||||||
Options,
|
|
||||||
Series,
|
|
||||||
Asset,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Field {
|
|
||||||
pub fn name(self) -> &'static str {
|
|
||||||
match self {
|
|
||||||
Field::Visible => "visible",
|
|
||||||
Field::A11yLabel => "a11y_label",
|
|
||||||
Field::Content => "content",
|
|
||||||
Field::Alt => "alt",
|
|
||||||
Field::Enabled => "enabled",
|
|
||||||
Field::Checked => "checked",
|
|
||||||
Field::Value => "value",
|
|
||||||
Field::Placeholder => "placeholder",
|
|
||||||
Field::Initial => "initial",
|
|
||||||
Field::Selected => "selected",
|
|
||||||
Field::Options => "options",
|
|
||||||
Field::Series => "series",
|
|
||||||
Field::Asset => "asset",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Why a site or a Repeat has no value. `detail` names the fault and never carries a state value.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub struct BindError {
|
|
||||||
pub code: Code,
|
|
||||||
pub detail: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What one site shows. A value is never coerced into another site type.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub enum Bound {
|
|
||||||
Text(String),
|
|
||||||
Number(f64),
|
|
||||||
Bool(bool),
|
|
||||||
Series(Vec<f64>),
|
|
||||||
Options(Vec<SelectOption>),
|
|
||||||
/// The catalog entry an Image names.
|
|
||||||
Asset(AssetEntry),
|
|
||||||
/// The record or the member is not there (or is nil).
|
|
||||||
Absent,
|
|
||||||
Error(BindError),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One instance of a Repeat's template: its key, and the template with derived ids, whose sites
|
|
||||||
/// are in the same table. A refused item's key is `!` and its record key.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct Instance {
|
|
||||||
pub key: String,
|
|
||||||
pub root: thing_contract::Node,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The values of one resolved document.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct BoundTree {
|
|
||||||
tree: ResolvedTree,
|
|
||||||
values: HashMap<(NodeId, Field), Bound>,
|
|
||||||
instances: HashMap<NodeId, Vec<Instance>>,
|
|
||||||
repeat_errors: HashMap<NodeId, BindError>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl BoundTree {
|
|
||||||
pub fn resolved(&self) -> &ResolvedTree {
|
|
||||||
&self.tree
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn value(&self, node: &NodeId, field: Field) -> Option<&Bound> {
|
|
||||||
self.values.get(&(node.clone(), field))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The instances of a Repeat, in collection order; none when the Repeat is in error.
|
|
||||||
pub fn instances(&self, repeat: &NodeId) -> &[Instance] {
|
|
||||||
self.instances.get(repeat).map_or(&[], Vec::as_slice)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Why a Repeat has no instances, when it is in error.
|
|
||||||
pub fn repeat_error(&self, repeat: &NodeId) -> Option<&BindError> {
|
|
||||||
self.repeat_errors.get(repeat)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every bound site, instances' included, sorted by node id and field.
|
|
||||||
pub fn sites(&self) -> Vec<(&NodeId, Field, &Bound)> {
|
|
||||||
let mut sites: Vec<_> = self.values.iter().map(|((node, field), bound)| (node, *field, bound)).collect();
|
|
||||||
sites.sort_by(|a, b| (a.0.as_str(), a.1).cmp(&(b.0.as_str(), b.1)));
|
|
||||||
sites
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What one bind or apply changed: per surface key, the node ids whose value changed (appeared,
|
|
||||||
/// vanished or differed) or whose Repeat instance set changed; and the diagnostics of sites that
|
|
||||||
/// entered an error or changed error code.
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq)]
|
|
||||||
pub struct Applied {
|
|
||||||
pub dirty: BTreeMap<String, Vec<NodeId>>,
|
|
||||||
pub diagnostics: Vec<Diagnostic>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What a surface's unit read and owns, so a unit can be replaced alone.
|
|
||||||
struct Owned {
|
|
||||||
values: Vec<(NodeId, Field)>,
|
|
||||||
repeats: Vec<NodeId>,
|
|
||||||
ids: Vec<NodeId>,
|
|
||||||
nodes: usize,
|
|
||||||
interests: HashSet<Interest>,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Surface {
|
|
||||||
key: String,
|
|
||||||
bound: BoundTree,
|
|
||||||
tree_ids: HashSet<NodeId>,
|
|
||||||
parts: HashMap<Unit, Owned>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Binder {
|
|
||||||
limits: Limits,
|
|
||||||
surfaces: HashMap<String, Surface>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn tree_ids(tree: &ResolvedTree) -> HashSet<NodeId> {
|
|
||||||
fn visit(node: &thing_contract::Node, out: &mut HashSet<NodeId>) {
|
|
||||||
crate::resolve::grow(|| {
|
|
||||||
out.extend(walk::common(node).map(|common| common.id.clone()));
|
|
||||||
if let thing_contract::Node::Repeat(repeat) = node {
|
|
||||||
visit(&repeat.template, out);
|
|
||||||
}
|
|
||||||
walk::children(node).iter().for_each(|child| visit(child, out));
|
|
||||||
})
|
|
||||||
}
|
|
||||||
let mut ids = HashSet::new();
|
|
||||||
visit(&tree.document().root, &mut ids);
|
|
||||||
ids
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Surface {
|
|
||||||
fn interests(&self) -> HashSet<Interest> {
|
|
||||||
self.parts.values().flat_map(|owned| owned.interests.iter().cloned()).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Bind the units `only` selects (all when `None`), replace what they owned, and report what
|
|
||||||
/// changed against what they held.
|
|
||||||
fn run(
|
|
||||||
&mut self,
|
|
||||||
limits: &Limits,
|
|
||||||
port: &mut dyn StatePort,
|
|
||||||
ledger: &mut Ledger,
|
|
||||||
only: Option<&HashSet<Unit>>,
|
|
||||||
) -> (Vec<NodeId>, Vec<Diagnostic>) {
|
|
||||||
let before = self.interests();
|
|
||||||
let mut old_values: HashMap<(NodeId, Field), Bound> = HashMap::new();
|
|
||||||
let mut old_keys: HashMap<NodeId, Vec<String>> = HashMap::new();
|
|
||||||
let mut old_errors: HashMap<NodeId, Code> = HashMap::new();
|
|
||||||
let retired: Vec<Unit> = match only {
|
|
||||||
None => self.parts.keys().cloned().collect(),
|
|
||||||
Some(only) => only.iter().filter(|unit| self.parts.contains_key(*unit)).cloned().collect(),
|
|
||||||
};
|
|
||||||
for unit in retired {
|
|
||||||
let Some(owned) = self.parts.remove(&unit) else { continue };
|
|
||||||
for key in owned.values {
|
|
||||||
if let Some(bound) = self.bound.values.remove(&key) {
|
|
||||||
old_values.insert(key, bound);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for repeat in owned.repeats {
|
|
||||||
if let Some(instances) = self.bound.instances.remove(&repeat) {
|
|
||||||
old_keys.insert(repeat.clone(), instances.into_iter().map(|instance| instance.key).collect());
|
|
||||||
}
|
|
||||||
if let Some(error) = self.bound.repeat_errors.remove(&repeat) {
|
|
||||||
old_errors.insert(repeat, error.code);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut taken = self.tree_ids.clone();
|
|
||||||
let mut spent = 0;
|
|
||||||
for owned in self.parts.values() {
|
|
||||||
taken.extend(owned.ids.iter().cloned());
|
|
||||||
spent += owned.nodes;
|
|
||||||
}
|
|
||||||
let provider = self.bound.tree.document().provider_id.clone();
|
|
||||||
let parts = Walker::new(&*port, &provider, limits, taken, limits.max_nodes.saturating_sub(spent), only)
|
|
||||||
.run(&self.bound.tree.document().root);
|
|
||||||
|
|
||||||
let mut diagnostics = Vec::new();
|
|
||||||
let mut dirty: Vec<NodeId> = Vec::new();
|
|
||||||
let mut note = |node: &NodeId, code: Code, detail: &str, was: Option<Code>| {
|
|
||||||
if was != Some(code) {
|
|
||||||
diagnostics.push(Diagnostic { code, surface: self.key.clone(), node: Some(node.clone()), detail: detail.to_string() });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
for (unit, part) in parts {
|
|
||||||
let mut owned = Owned {
|
|
||||||
values: Vec::new(),
|
|
||||||
repeats: Vec::new(),
|
|
||||||
ids: part.ids,
|
|
||||||
nodes: part.nodes,
|
|
||||||
interests: part.interests,
|
|
||||||
};
|
|
||||||
for (key, bound) in part.values {
|
|
||||||
let old = old_values.remove(&key);
|
|
||||||
if old.as_ref() != Some(&bound) {
|
|
||||||
dirty.push(key.0.clone());
|
|
||||||
}
|
|
||||||
if let Bound::Error(error) = &bound {
|
|
||||||
note(&key.0, error.code, &error.detail, match &old {
|
|
||||||
Some(Bound::Error(was)) => Some(was.code),
|
|
||||||
_ => None,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
owned.values.push(key.clone());
|
|
||||||
self.bound.values.insert(key, bound);
|
|
||||||
}
|
|
||||||
for (repeat, error) in part.errors {
|
|
||||||
note(&repeat, error.code, &error.detail, old_errors.get(&repeat).copied());
|
|
||||||
self.bound.repeat_errors.insert(repeat, error);
|
|
||||||
}
|
|
||||||
for (repeat, instances) in part.instances {
|
|
||||||
let keys: Vec<String> = instances.iter().map(|instance| instance.key.clone()).collect();
|
|
||||||
if old_keys.remove(&repeat).as_ref() != Some(&keys) {
|
|
||||||
dirty.push(repeat.clone());
|
|
||||||
}
|
|
||||||
owned.repeats.push(repeat.clone());
|
|
||||||
self.bound.instances.insert(repeat, instances);
|
|
||||||
}
|
|
||||||
self.parts.insert(unit, owned);
|
|
||||||
}
|
|
||||||
// What the retired units held and the new ones no longer do has vanished.
|
|
||||||
dirty.extend(old_values.into_keys().map(|(node, _)| node));
|
|
||||||
dirty.extend(old_keys.into_keys());
|
|
||||||
|
|
||||||
ledger.diff(port, &before, &self.interests());
|
|
||||||
let mut seen = HashSet::new();
|
|
||||||
dirty.retain(|node| seen.insert(node.clone()));
|
|
||||||
dirty.sort_by(|a, b| a.as_str().cmp(b.as_str()));
|
|
||||||
(dirty, diagnostics)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn matching(&self, address: &Address) -> HashSet<Unit> {
|
|
||||||
self.parts
|
|
||||||
.iter()
|
|
||||||
.filter(|(_, owned)| owned.interests.iter().any(|interest| interest.matches(address)))
|
|
||||||
.map(|(unit, _)| unit.clone())
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Binder {
|
|
||||||
pub fn new(limits: Limits) -> Self {
|
|
||||||
Self { limits, surfaces: HashMap::new() }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Bind a resolved tree. A tree for a surface already held replaces its tree: the walk, the
|
|
||||||
/// diff against what was bound and the interest diff are the same as an apply's.
|
|
||||||
pub fn bind(&mut self, tree: ResolvedTree, port: &mut dyn StatePort, ledger: &mut Ledger) -> Applied {
|
|
||||||
let key = tree.document().record_key();
|
|
||||||
let ids = tree_ids(&tree);
|
|
||||||
let surface = self.surfaces.entry(key.clone()).or_insert_with(|| Surface {
|
|
||||||
key: key.clone(),
|
|
||||||
bound: BoundTree {
|
|
||||||
tree: tree.clone(),
|
|
||||||
values: HashMap::new(),
|
|
||||||
instances: HashMap::new(),
|
|
||||||
repeat_errors: HashMap::new(),
|
|
||||||
},
|
|
||||||
tree_ids: HashSet::new(),
|
|
||||||
parts: HashMap::new(),
|
|
||||||
});
|
|
||||||
surface.bound.tree = tree;
|
|
||||||
surface.tree_ids = ids;
|
|
||||||
let (dirty, diagnostics) = surface.run(&self.limits, port, ledger, None);
|
|
||||||
Applied { dirty: BTreeMap::from([(key, dirty)]).into_iter().filter(|(_, ids)| !ids.is_empty()).collect(), diagnostics }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One drained change: nothing is read unless a held interest matches its address; then each
|
|
||||||
/// unit that read it is bound again from the port.
|
|
||||||
pub fn apply(&mut self, change: &Change, port: &mut dyn StatePort, ledger: &mut Ledger) -> Applied {
|
|
||||||
let address = match change {
|
|
||||||
Change::Upsert(entry) => &entry.address,
|
|
||||||
Change::Delete(address) => address,
|
|
||||||
Change::Refused(refusal) => &refusal.address,
|
|
||||||
};
|
|
||||||
let mut applied = Applied::default();
|
|
||||||
let mut keys: Vec<String> = self.surfaces.keys().cloned().collect();
|
|
||||||
keys.sort();
|
|
||||||
for key in keys {
|
|
||||||
let surface = self.surfaces.get_mut(&key).expect("key listed");
|
|
||||||
let units = surface.matching(address);
|
|
||||||
if units.is_empty() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let (dirty, diagnostics) = surface.run(&self.limits, port, ledger, Some(&units));
|
|
||||||
if !dirty.is_empty() {
|
|
||||||
applied.dirty.insert(key, dirty);
|
|
||||||
}
|
|
||||||
applied.diagnostics.extend(diagnostics);
|
|
||||||
}
|
|
||||||
applied
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Drop a surface: its interests are released.
|
|
||||||
pub fn forget(&mut self, surface: &str, port: &mut dyn StatePort, ledger: &mut Ledger) {
|
|
||||||
if let Some(surface) = self.surfaces.remove(surface) {
|
|
||||||
ledger.diff(port, &surface.interests(), &HashSet::new());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn tree(&self, surface: &str) -> Option<&BoundTree> {
|
|
||||||
self.surfaces.get(surface).map(|surface| &surface.bound)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,199 +0,0 @@
|
||||||
//! Repeat: a collection's items become instances of the template, keyed so identity follows the
|
|
||||||
//! item. An instance's ids derive from (repeat id, key, template id) by one scheme:
|
|
||||||
//! `<repeat>#<key byte length>:<key>/<template id>`; an item the port refused has no key to read,
|
|
||||||
//! so its identity is its record key in the distinct form `<repeat>!<length>:<record key>/<template id>`.
|
|
||||||
//! A Repeat that cannot be instantiated is an error of that Repeat alone.
|
|
||||||
|
|
||||||
use std::collections::HashSet;
|
|
||||||
|
|
||||||
use thing_contract::*;
|
|
||||||
|
|
||||||
use super::walk::{Item, Walker, children, common, fault, walk};
|
|
||||||
use super::{BindError, Instance};
|
|
||||||
use crate::diagnostic::Code;
|
|
||||||
use crate::port::{Lookup, Prefix, Record, StateValue};
|
|
||||||
use crate::resolve::grow;
|
|
||||||
|
|
||||||
/// One item of a collection. `record_key` is set for an item that is a record of its own.
|
|
||||||
pub(super) struct Entry {
|
|
||||||
pub record_key: Option<String>,
|
|
||||||
pub item: Item,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The key of an item: Text as it is, an Int in decimal.
|
|
||||||
fn key_of(value: &StateValue, path: &MemberPath) -> Result<String, BindError> {
|
|
||||||
match walk(value, path)? {
|
|
||||||
Some(StateValue::Text(text)) => Ok(text.clone()),
|
|
||||||
Some(StateValue::Int(n)) => Ok(n.to_string()),
|
|
||||||
Some(_) => Err(fault(Code::BindTypeMismatch, "an item key is not Text or Int")),
|
|
||||||
None => Err(fault(Code::BindTypeMismatch, "an item key is nil")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn collect_ids(node: &Node, out: &mut Vec<NodeId>) {
|
|
||||||
grow(|| {
|
|
||||||
out.extend(common(node).map(|common| common.id.clone()));
|
|
||||||
if let Node::Repeat(repeat) = node {
|
|
||||||
collect_ids(&repeat.template, out);
|
|
||||||
}
|
|
||||||
children(node).iter().for_each(|child| collect_ids(child, out));
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Give every id of the template, and every anchor that names one of them, the instance prefix.
|
|
||||||
fn rewrite(node: &mut Node, prefix: &str, inside: &HashSet<NodeId>) {
|
|
||||||
grow(|| {
|
|
||||||
let derive = |id: &mut NodeId| *id = NodeId::new(format!("{prefix}{}", id.as_str()));
|
|
||||||
match node {
|
|
||||||
Node::Box(n) => {
|
|
||||||
derive(&mut n.common.id);
|
|
||||||
n.children.iter_mut().for_each(|child| rewrite(child, prefix, inside));
|
|
||||||
}
|
|
||||||
Node::Button(n) => {
|
|
||||||
derive(&mut n.common.id);
|
|
||||||
n.content.iter_mut().for_each(|child| rewrite(child, prefix, inside));
|
|
||||||
}
|
|
||||||
Node::Overlay(n) => {
|
|
||||||
derive(&mut n.common.id);
|
|
||||||
if let Anchor::Node(anchor) = &mut n.anchor {
|
|
||||||
if inside.contains(&anchor.node) {
|
|
||||||
derive(&mut anchor.node);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
n.children.iter_mut().for_each(|child| rewrite(child, prefix, inside));
|
|
||||||
}
|
|
||||||
Node::Repeat(n) => {
|
|
||||||
derive(&mut n.common.id);
|
|
||||||
rewrite(&mut n.template, prefix, inside);
|
|
||||||
}
|
|
||||||
Node::Text(n) => derive(&mut n.common.id),
|
|
||||||
Node::Image(n) => derive(&mut n.common.id),
|
|
||||||
Node::Toggle(n) => derive(&mut n.common.id),
|
|
||||||
Node::Slider(n) => derive(&mut n.common.id),
|
|
||||||
Node::TextInput(n) => derive(&mut n.common.id),
|
|
||||||
Node::Select(n) => derive(&mut n.common.id),
|
|
||||||
Node::Plot(n) => derive(&mut n.common.id),
|
|
||||||
Node::Embed(n) => derive(&mut n.common.id),
|
|
||||||
Node::Use(n) => derive(&mut n.common.id),
|
|
||||||
Node::Slot(_) => {}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Walker<'_> {
|
|
||||||
/// The items of a collection, each a value or the fault that stands for it. Records read the
|
|
||||||
/// prefix, a Member reads the list of its holder; both leave their interest.
|
|
||||||
pub(super) fn collection(&mut self, source: &CollectionSource, item: Option<&Item>) -> Result<Vec<Entry>, BindError> {
|
|
||||||
match source {
|
|
||||||
CollectionSource::Records(records) => {
|
|
||||||
let provider = records.provider.clone().unwrap_or_else(|| self.provider.clone());
|
|
||||||
let prefix = Prefix { provider, schema: records.schema.clone(), key_prefix: records.key_prefix.clone() };
|
|
||||||
self.part.interests.insert(crate::port::Interest::Prefix(prefix.clone()));
|
|
||||||
Ok(self
|
|
||||||
.port
|
|
||||||
.list(&prefix)
|
|
||||||
.into_iter()
|
|
||||||
.filter_map(|lookup| match lookup {
|
|
||||||
Lookup::Present(entry) => {
|
|
||||||
let record_key = Some(entry.address.key.as_str().to_string());
|
|
||||||
Some(match entry.record {
|
|
||||||
Record::State { schema, value } if schema == records.schema => {
|
|
||||||
Entry { record_key, item: Item::Value(value) }
|
|
||||||
}
|
|
||||||
_ => Entry {
|
|
||||||
record_key,
|
|
||||||
item: Item::Fault(fault(
|
|
||||||
Code::BindSchemaMismatch,
|
|
||||||
format!("the record is not held under {}", records.schema.as_str()),
|
|
||||||
)),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
Lookup::Refused(refusal) => Some(Entry {
|
|
||||||
record_key: Some(refusal.address.key.as_str().to_string()),
|
|
||||||
item: Item::Fault(fault(Code::DecodeRefused, refusal.detail)),
|
|
||||||
}),
|
|
||||||
Lookup::Absent => None,
|
|
||||||
})
|
|
||||||
.collect())
|
|
||||||
}
|
|
||||||
CollectionSource::Member(bind) => self.with_source(&bind.source, item, |held| match held? {
|
|
||||||
None => Ok(Vec::new()),
|
|
||||||
Some(holder) => match walk(holder, &bind.member)? {
|
|
||||||
None => Ok(Vec::new()),
|
|
||||||
Some(StateValue::List(items)) => Ok(items
|
|
||||||
.iter()
|
|
||||||
.map(|value| Entry { record_key: None, item: Item::Value(value.clone()) })
|
|
||||||
.collect()),
|
|
||||||
Some(_) => Err(fault(Code::BindTypeMismatch, "a collection member is not a list")),
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
CollectionSource::Param(_) => {
|
|
||||||
Err(fault(Code::BindTypeMismatch, "a parameter that resolve left in the tree"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Bind the instances of one Repeat, whole or not at all.
|
|
||||||
pub(super) fn repeat(&mut self, repeat: &RepeatNode, outer: Option<&Item>) {
|
|
||||||
let id = repeat.common.id.clone();
|
|
||||||
match self.instances(repeat, outer) {
|
|
||||||
Ok(instances) => self.part.instances.push((id, instances)),
|
|
||||||
Err(error) => {
|
|
||||||
self.part.errors.push((id.clone(), error));
|
|
||||||
self.part.instances.push((id, Vec::new()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn instances(&mut self, repeat: &RepeatNode, outer: Option<&Item>) -> Result<Vec<Instance>, BindError> {
|
|
||||||
let entries = self.collection(&repeat.collection, outer)?;
|
|
||||||
let id = repeat.common.id.as_str();
|
|
||||||
let mut template_ids = Vec::new();
|
|
||||||
collect_ids(&repeat.template, &mut template_ids);
|
|
||||||
let inside: HashSet<NodeId> = template_ids.into_iter().collect();
|
|
||||||
|
|
||||||
let mut keys = HashSet::new();
|
|
||||||
let mut built: Vec<(Instance, Item)> = Vec::with_capacity(entries.len());
|
|
||||||
for entry in entries {
|
|
||||||
let (key, prefix) = match &entry.item {
|
|
||||||
Item::Fault(_) => {
|
|
||||||
let record = entry.record_key.clone().unwrap_or_default();
|
|
||||||
(format!("!{record}"), format!("{id}!{}:{record}/", record.len()))
|
|
||||||
}
|
|
||||||
Item::Value(value) => {
|
|
||||||
let key = key_of(value, &repeat.key_member)?;
|
|
||||||
if !keys.insert(key.clone()) {
|
|
||||||
return Err(fault(Code::RepeatKeyDuplicate, format!("two items of {id} share one key")));
|
|
||||||
}
|
|
||||||
let prefix = format!("{id}#{}:{key}/", key.len());
|
|
||||||
(key, prefix)
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let mut root = (*repeat.template).clone();
|
|
||||||
rewrite(&mut root, &prefix, &inside);
|
|
||||||
built.push((Instance { key, root }, entry.item));
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut ids = Vec::new();
|
|
||||||
for (instance, _) in &built {
|
|
||||||
collect_ids(&instance.root, &mut ids);
|
|
||||||
}
|
|
||||||
if ids.len() > self.budget.min(self.limits.max_nodes) {
|
|
||||||
return Err(fault(Code::ExpansionLimit, format!("the instances of {id} are past the node limit")));
|
|
||||||
}
|
|
||||||
let mut local = HashSet::new();
|
|
||||||
if ids.iter().any(|derived| self.taken.contains(derived) || !local.insert(derived)) {
|
|
||||||
return Err(fault(Code::DuplicateNodeId, format!("an instance id of {id} is already an id of the tree")));
|
|
||||||
}
|
|
||||||
|
|
||||||
self.budget -= ids.len();
|
|
||||||
self.part.nodes += ids.len();
|
|
||||||
self.taken.extend(ids.iter().cloned());
|
|
||||||
self.part.ids.extend(ids);
|
|
||||||
for (instance, item) in &built {
|
|
||||||
self.instance(&instance.root, item);
|
|
||||||
}
|
|
||||||
Ok(built.into_iter().map(|(instance, _)| instance).collect())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,402 +0,0 @@
|
||||||
//! The walk: every source site of a node, read from the state port, a member path and a terminal
|
|
||||||
//! type. Nothing here keeps a value: the port is the truth.
|
|
||||||
|
|
||||||
use std::collections::HashSet;
|
|
||||||
|
|
||||||
use thing_contract::*;
|
|
||||||
|
|
||||||
use super::format;
|
|
||||||
use super::{BindError, Bound, Field, Instance};
|
|
||||||
use crate::diagnostic::Code;
|
|
||||||
use crate::port::{Address, Entry, Interest, Lookup, Record, StatePort, StateValue};
|
|
||||||
use crate::resolve::{Limits, grow};
|
|
||||||
|
|
||||||
/// What a surface's values are re-evaluated by: one site, or one outermost Repeat (`None`).
|
|
||||||
pub(super) type Unit = (NodeId, Option<Field>);
|
|
||||||
|
|
||||||
/// What one unit bound: its values, its instance lists, its Repeat faults, the ids and node count
|
|
||||||
/// its instances take, and the interests it read.
|
|
||||||
#[derive(Default)]
|
|
||||||
pub(super) struct Part {
|
|
||||||
pub values: Vec<((NodeId, Field), Bound)>,
|
|
||||||
pub instances: Vec<(NodeId, Vec<Instance>)>,
|
|
||||||
pub errors: Vec<(NodeId, BindError)>,
|
|
||||||
pub ids: Vec<NodeId>,
|
|
||||||
pub nodes: usize,
|
|
||||||
pub interests: HashSet<Interest>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The value a Repeat's template reads through `Item`.
|
|
||||||
pub(super) enum Item {
|
|
||||||
Value(StateValue),
|
|
||||||
Fault(BindError),
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn fault(code: Code, detail: impl Into<String>) -> BindError {
|
|
||||||
BindError { code, detail: detail.into() }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
|
||||||
pub(super) enum Want {
|
|
||||||
Text,
|
|
||||||
Number,
|
|
||||||
Bool,
|
|
||||||
Series,
|
|
||||||
}
|
|
||||||
|
|
||||||
enum Site<'n> {
|
|
||||||
Bool(&'n BoolSource),
|
|
||||||
Text(&'n TextSource),
|
|
||||||
Number(&'n NumberSource),
|
|
||||||
Bind(&'n Bind, Want),
|
|
||||||
Options(&'n OptionList),
|
|
||||||
Asset(&'n ImageNode),
|
|
||||||
}
|
|
||||||
|
|
||||||
fn kind(value: &StateValue) -> &'static str {
|
|
||||||
match value {
|
|
||||||
StateValue::Nil => "nil",
|
|
||||||
StateValue::Bool(_) => "bool",
|
|
||||||
StateValue::Int(_) => "int",
|
|
||||||
StateValue::Float(_) => "float",
|
|
||||||
StateValue::Text(_) => "text",
|
|
||||||
StateValue::Bytes(_) => "bytes",
|
|
||||||
StateValue::List(_) => "list",
|
|
||||||
StateValue::Record(_) => "record",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn number_of(value: &StateValue) -> Option<f64> {
|
|
||||||
match value {
|
|
||||||
StateValue::Int(n) => Some(*n as f64),
|
|
||||||
StateValue::Float(n) => Some(*n),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Walk `path` from `value`. `Ok(None)` is a Nil reached, which is absence.
|
|
||||||
pub(super) fn walk<'v>(mut value: &'v StateValue, path: &MemberPath) -> Result<Option<&'v StateValue>, BindError> {
|
|
||||||
for step in &path.steps {
|
|
||||||
if matches!(value, StateValue::Nil) {
|
|
||||||
return Ok(None);
|
|
||||||
}
|
|
||||||
value = match (step, value) {
|
|
||||||
(MemberStep::Name(step), StateValue::Record(_)) => value
|
|
||||||
.member(&step.name)
|
|
||||||
.ok_or_else(|| fault(Code::BindMemberMissing, format!("the record has no member {}", step.name)))?,
|
|
||||||
(MemberStep::Index(step), StateValue::List(items)) => items.get(step.index.get() as usize).ok_or_else(|| {
|
|
||||||
fault(Code::BindMemberMissing, format!("the list has no index {}", step.index.get()))
|
|
||||||
})?,
|
|
||||||
(MemberStep::Name(step), other) => {
|
|
||||||
return Err(fault(Code::BindTypeMismatch, format!("member {} asked of a {}", step.name, kind(other))));
|
|
||||||
}
|
|
||||||
(MemberStep::Index(step), other) => {
|
|
||||||
return Err(fault(Code::BindTypeMismatch, format!("index {} asked of a {}", step.index.get(), kind(other))));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
Ok(if matches!(value, StateValue::Nil) { None } else { Some(value) })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A value at the type its site takes. No value is coerced; a Format is the only road from a
|
|
||||||
/// number to text.
|
|
||||||
fn terminal(value: &StateValue, want: Want, format: Option<&Format>) -> Result<Bound, BindError> {
|
|
||||||
let mismatch = |why: &str| Err(fault(Code::BindTypeMismatch, format!("{why}: a {} value", kind(value))));
|
|
||||||
if want != Want::Text && format.is_some() {
|
|
||||||
return mismatch("a Format on a site that is not text");
|
|
||||||
}
|
|
||||||
match want {
|
|
||||||
Want::Number => match number_of(value) {
|
|
||||||
Some(n) => Ok(Bound::Number(n)),
|
|
||||||
None => mismatch("a number site"),
|
|
||||||
},
|
|
||||||
Want::Bool => match value {
|
|
||||||
StateValue::Bool(b) => Ok(Bound::Bool(*b)),
|
|
||||||
_ => mismatch("a bool site"),
|
|
||||||
},
|
|
||||||
Want::Series => match value {
|
|
||||||
StateValue::List(items) => match items.iter().map(number_of).collect::<Option<Vec<f64>>>() {
|
|
||||||
Some(series) => Ok(Bound::Series(series)),
|
|
||||||
None => Err(fault(Code::BindTypeMismatch, "a series holds a member that is not a number")),
|
|
||||||
},
|
|
||||||
_ => mismatch("a series site"),
|
|
||||||
},
|
|
||||||
Want::Text => {
|
|
||||||
let text = match (value, format) {
|
|
||||||
(StateValue::Text(text), None) => Ok(text.clone()),
|
|
||||||
(StateValue::Text(text), Some(Format::Affix(affix))) => Ok(format::affix(text, affix)),
|
|
||||||
(StateValue::Text(text), Some(Format::Timestamp)) => format::stamp(text),
|
|
||||||
(StateValue::Int(_) | StateValue::Float(_), Some(Format::Number(spec))) => {
|
|
||||||
Ok(format::number(number_of(value).unwrap(), spec))
|
|
||||||
}
|
|
||||||
(StateValue::Int(_) | StateValue::Float(_), Some(Format::Duration)) => {
|
|
||||||
format::duration(number_of(value).unwrap())
|
|
||||||
}
|
|
||||||
(StateValue::Int(_) | StateValue::Float(_), Some(Format::Timestamp)) => {
|
|
||||||
format::timestamp(number_of(value).unwrap())
|
|
||||||
}
|
|
||||||
_ => Err("the value does not fit the text site and its Format"),
|
|
||||||
};
|
|
||||||
text.map(Bound::Text).map_err(|why| fault(Code::BindTypeMismatch, format!("{why}: a {} value", kind(value))))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The Text at `path` of an item, for an option's value or label.
|
|
||||||
pub(super) fn item_text(value: &StateValue, path: &MemberPath) -> Result<String, BindError> {
|
|
||||||
match walk(value, path)? {
|
|
||||||
Some(StateValue::Text(text)) => Ok(text.clone()),
|
|
||||||
Some(other) => Err(fault(Code::BindTypeMismatch, format!("an option member is a {}", kind(other)))),
|
|
||||||
None => Err(fault(Code::BindTypeMismatch, "an option member is nil")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The sites of one node, in Field order.
|
|
||||||
fn sites(node: &Node) -> Vec<(Field, Site<'_>)> {
|
|
||||||
let mut found = Vec::new();
|
|
||||||
let Some(common) = common(node) else { return found };
|
|
||||||
found.push((Field::Visible, Site::Bool(&common.visible)));
|
|
||||||
if let Some(label) = &common.a11y_label {
|
|
||||||
found.push((Field::A11yLabel, Site::Text(label)));
|
|
||||||
}
|
|
||||||
match node {
|
|
||||||
Node::Text(n) => found.push((Field::Content, Site::Text(&n.content))),
|
|
||||||
Node::Image(n) => {
|
|
||||||
found.push((Field::Alt, Site::Text(&n.alt)));
|
|
||||||
found.push((Field::Asset, Site::Asset(n)));
|
|
||||||
}
|
|
||||||
Node::Button(n) => found.push((Field::Enabled, Site::Bool(&n.enabled))),
|
|
||||||
Node::Toggle(n) => found.push((Field::Checked, Site::Bool(&n.checked))),
|
|
||||||
Node::Slider(n) => found.push((Field::Value, Site::Number(&n.value))),
|
|
||||||
Node::TextInput(n) => {
|
|
||||||
found.push((Field::Placeholder, Site::Text(&n.placeholder)));
|
|
||||||
found.push((Field::Initial, Site::Text(&n.initial)));
|
|
||||||
}
|
|
||||||
Node::Select(n) => {
|
|
||||||
found.push((Field::Options, Site::Options(&n.options)));
|
|
||||||
found.push((Field::Selected, Site::Bind(&n.value, Want::Text)));
|
|
||||||
}
|
|
||||||
Node::Plot(n) => found.push((Field::Series, Site::Bind(&n.series, Want::Series))),
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
found
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn common(node: &Node) -> Option<&NodeCommon> {
|
|
||||||
Some(match node {
|
|
||||||
Node::Box(n) => &n.common,
|
|
||||||
Node::Text(n) => &n.common,
|
|
||||||
Node::Image(n) => &n.common,
|
|
||||||
Node::Button(n) => &n.common,
|
|
||||||
Node::Toggle(n) => &n.common,
|
|
||||||
Node::Slider(n) => &n.common,
|
|
||||||
Node::TextInput(n) => &n.common,
|
|
||||||
Node::Select(n) => &n.common,
|
|
||||||
Node::Repeat(n) => &n.common,
|
|
||||||
Node::Overlay(n) => &n.common,
|
|
||||||
Node::Plot(n) => &n.common,
|
|
||||||
Node::Embed(n) => &n.common,
|
|
||||||
Node::Use(n) => &n.common,
|
|
||||||
Node::Slot(_) => return None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The children a walk visits: a Repeat's template is instantiated, never visited as itself.
|
|
||||||
pub(super) fn children(node: &Node) -> &[Node] {
|
|
||||||
match node {
|
|
||||||
Node::Box(n) => &n.children,
|
|
||||||
Node::Button(n) => &n.content,
|
|
||||||
Node::Overlay(n) => &n.children,
|
|
||||||
_ => &[],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) struct Walker<'a> {
|
|
||||||
pub(super) port: &'a dyn StatePort,
|
|
||||||
pub(super) provider: &'a ProviderId,
|
|
||||||
pub(super) limits: &'a Limits,
|
|
||||||
/// Every id of the bound tree outside the units being walked, and the ones walked so far.
|
|
||||||
pub(super) taken: HashSet<NodeId>,
|
|
||||||
/// Instance nodes still allowed.
|
|
||||||
pub(super) budget: usize,
|
|
||||||
only: Option<&'a HashSet<Unit>>,
|
|
||||||
pub(super) part: Part,
|
|
||||||
done: Vec<(Unit, Part)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> Walker<'a> {
|
|
||||||
pub(super) fn new(
|
|
||||||
port: &'a dyn StatePort,
|
|
||||||
provider: &'a ProviderId,
|
|
||||||
limits: &'a Limits,
|
|
||||||
taken: HashSet<NodeId>,
|
|
||||||
budget: usize,
|
|
||||||
only: Option<&'a HashSet<Unit>>,
|
|
||||||
) -> Self {
|
|
||||||
Self { port, provider, limits, taken, budget, only, part: Part::default(), done: Vec::new() }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Walk the resolved root, binding every unit `only` selects (all when `None`).
|
|
||||||
pub(super) fn run(mut self, root: &Node) -> Vec<(Unit, Part)> {
|
|
||||||
self.top(root);
|
|
||||||
self.done
|
|
||||||
}
|
|
||||||
|
|
||||||
fn selects(&self, unit: &Unit) -> bool {
|
|
||||||
self.only.is_none_or(|only| only.contains(unit))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn end(&mut self, unit: Unit) {
|
|
||||||
let part = std::mem::take(&mut self.part);
|
|
||||||
self.done.push((unit, part));
|
|
||||||
}
|
|
||||||
|
|
||||||
fn top(&mut self, node: &Node) {
|
|
||||||
grow(|| {
|
|
||||||
let Some(id) = common(node).map(|common| common.id.clone()) else { return };
|
|
||||||
for (field, site) in sites(node) {
|
|
||||||
let unit = (id.clone(), Some(field));
|
|
||||||
if self.selects(&unit) {
|
|
||||||
let value = self.eval(site, None);
|
|
||||||
self.part.values.push(((id.clone(), field), value));
|
|
||||||
self.end(unit);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if let Node::Repeat(repeat) = node {
|
|
||||||
let unit = (id, None);
|
|
||||||
if self.selects(&unit) {
|
|
||||||
self.repeat(repeat, None);
|
|
||||||
self.end(unit);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
children(node).iter().for_each(|child| self.top(child));
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An instance's nodes: every site binds, with `item` as the Item.
|
|
||||||
pub(super) fn instance(&mut self, node: &Node, item: &Item) {
|
|
||||||
grow(|| {
|
|
||||||
let Some(id) = common(node).map(|common| common.id.clone()) else { return };
|
|
||||||
for (field, site) in sites(node) {
|
|
||||||
let value = self.eval(site, Some(item));
|
|
||||||
self.part.values.push(((id.clone(), field), value));
|
|
||||||
}
|
|
||||||
if let Node::Repeat(repeat) = node {
|
|
||||||
self.repeat(repeat, Some(item));
|
|
||||||
} else {
|
|
||||||
children(node).iter().for_each(|child| self.instance(child, item));
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn eval(&mut self, site: Site<'_>, item: Option<&Item>) -> Bound {
|
|
||||||
let unresolved = || Bound::Error(fault(Code::BindTypeMismatch, "a parameter that resolve left in the tree"));
|
|
||||||
match site {
|
|
||||||
Site::Bool(BoolSource::Literal(literal)) => Bound::Bool(literal.value),
|
|
||||||
Site::Bool(BoolSource::Bound(bind)) => self.bind(bind, Want::Bool, item),
|
|
||||||
Site::Text(TextSource::Literal(literal)) => Bound::Text(literal.value.clone()),
|
|
||||||
Site::Text(TextSource::Bound(bind)) => self.bind(bind, Want::Text, item),
|
|
||||||
Site::Number(NumberSource::Literal(literal)) => Bound::Number(literal.value),
|
|
||||||
Site::Number(NumberSource::Bound(bind)) => self.bind(bind, Want::Number, item),
|
|
||||||
Site::Bool(BoolSource::Param(_)) | Site::Text(TextSource::Param(_)) | Site::Number(NumberSource::Param(_)) => {
|
|
||||||
unresolved()
|
|
||||||
}
|
|
||||||
Site::Bind(bind, want) => self.bind(bind, want, item),
|
|
||||||
Site::Options(OptionList::Literal(literal)) => Bound::Options(literal.options.clone()),
|
|
||||||
Site::Options(OptionList::Bound(bound)) => self.options(bound, item),
|
|
||||||
Site::Asset(image) => self.asset(image),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Hand `then` what `source` holds: a fault, absence, or the value. Records the interest a
|
|
||||||
/// Record source reads.
|
|
||||||
pub(super) fn with_source<R>(
|
|
||||||
&mut self,
|
|
||||||
source: &StateSource,
|
|
||||||
item: Option<&Item>,
|
|
||||||
then: impl FnOnce(Result<Option<&StateValue>, BindError>) -> R,
|
|
||||||
) -> R {
|
|
||||||
match source {
|
|
||||||
StateSource::Item => match item {
|
|
||||||
Some(Item::Value(value)) => then(Ok(Some(value))),
|
|
||||||
Some(Item::Fault(error)) => then(Err(error.clone())),
|
|
||||||
None => then(Err(fault(Code::BindTypeMismatch, "an Item source outside a Repeat"))),
|
|
||||||
},
|
|
||||||
StateSource::Record(reference) => {
|
|
||||||
let provider = reference.provider.clone().unwrap_or_else(|| self.provider.clone());
|
|
||||||
let address = Address { provider, schema: reference.schema.clone(), key: reference.key.clone() };
|
|
||||||
self.part.interests.insert(Interest::Record(address.clone()));
|
|
||||||
match self.port.read(&address) {
|
|
||||||
Lookup::Present(Entry { record: Record::State { schema, value }, .. }) if schema == reference.schema => {
|
|
||||||
then(Ok(Some(&value)))
|
|
||||||
}
|
|
||||||
Lookup::Present(_) => then(Err(fault(
|
|
||||||
Code::BindSchemaMismatch,
|
|
||||||
format!("the record is not held under {}", reference.schema.as_str()),
|
|
||||||
))),
|
|
||||||
Lookup::Absent => then(Ok(None)),
|
|
||||||
Lookup::Refused(refusal) => then(Err(fault(Code::DecodeRefused, refusal.detail))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn bind(&mut self, bind: &Bind, want: Want, item: Option<&Item>) -> Bound {
|
|
||||||
self.with_source(&bind.source, item, |held| match held {
|
|
||||||
Err(error) => Bound::Error(error),
|
|
||||||
Ok(None) => Bound::Absent,
|
|
||||||
Ok(Some(value)) => match walk(value, &bind.member) {
|
|
||||||
Err(error) => Bound::Error(error),
|
|
||||||
Ok(None) => Bound::Absent,
|
|
||||||
Ok(Some(value)) => terminal(value, want, bind.format.as_ref()).unwrap_or_else(Bound::Error),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The catalog entry an Image names: the catalog record is one more interest of the Image.
|
|
||||||
fn asset(&mut self, image: &ImageNode) -> Bound {
|
|
||||||
let Ok(catalog) = Segment::new(image.catalog.as_str()) else {
|
|
||||||
return Bound::Error(fault(Code::AssetMissing, "catalog id is not one segment"));
|
|
||||||
};
|
|
||||||
let address = Address {
|
|
||||||
provider: self.provider.clone(),
|
|
||||||
schema: SchemaId::new(AssetCatalog::SCHEMA_NAME),
|
|
||||||
key: RecordKey::new(asset_catalog_key(self.provider, &catalog)),
|
|
||||||
};
|
|
||||||
self.part.interests.insert(Interest::Record(address.clone()));
|
|
||||||
match self.port.read(&address) {
|
|
||||||
Lookup::Present(Entry { record: Record::Catalog(held), .. }) => {
|
|
||||||
match held.assets.into_iter().find(|entry| entry.id == image.asset) {
|
|
||||||
Some(entry) => Bound::Asset(entry),
|
|
||||||
None => Bound::Error(fault(Code::AssetMissing, format!("no asset {} in the catalog", image.asset))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Lookup::Present(_) => Bound::Error(fault(
|
|
||||||
Code::BindSchemaMismatch,
|
|
||||||
format!("the record is not held under {}", AssetCatalog::SCHEMA_NAME),
|
|
||||||
)),
|
|
||||||
Lookup::Absent => Bound::Absent,
|
|
||||||
Lookup::Refused(refusal) => Bound::Error(fault(Code::DecodeRefused, refusal.detail)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn options(&mut self, bound: &BoundOptions, item: Option<&Item>) -> Bound {
|
|
||||||
let entries = match self.collection(&bound.collection, item) {
|
|
||||||
Ok(entries) => entries,
|
|
||||||
Err(error) => return Bound::Error(error),
|
|
||||||
};
|
|
||||||
let mut options = Vec::with_capacity(entries.len());
|
|
||||||
for entry in entries {
|
|
||||||
let value = match entry.item {
|
|
||||||
Item::Value(value) => value,
|
|
||||||
Item::Fault(error) => return Bound::Error(error),
|
|
||||||
};
|
|
||||||
match (item_text(&value, &bound.value_member), item_text(&value, &bound.label_member)) {
|
|
||||||
(Ok(value), Ok(label)) => options.push(SelectOption { value, label }),
|
|
||||||
(Err(error), _) | (_, Err(error)) => return Bound::Error(error),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Bound::Options(options)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,65 +0,0 @@
|
||||||
//! What core says about a document it could not take whole. The code set is closed: a later
|
|
||||||
//! cut adds its codes as reviewed changes, never as free strings.
|
|
||||||
|
|
||||||
use thing_contract::NodeId;
|
|
||||||
|
|
||||||
/// Why a document, or one node of it, was not taken as authored.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
|
||||||
pub enum Code {
|
|
||||||
/// The port refused the composition's bytes. A refusal is never absence.
|
|
||||||
DecodeRefused,
|
|
||||||
/// No composition is published at the named address.
|
|
||||||
UnresolvedUse,
|
|
||||||
/// A composition that uses itself through others, or a chain deeper than the limit.
|
|
||||||
CompositionCycle,
|
|
||||||
/// An argument, a body or a composition record that does not fit its Use.
|
|
||||||
CompositionInvalid,
|
|
||||||
/// A command no surface declaration names.
|
|
||||||
UndeclaredCommand,
|
|
||||||
/// Two nodes of the expanded tree share an id.
|
|
||||||
DuplicateNodeId,
|
|
||||||
/// A Param or a Slot outside any composition.
|
|
||||||
UnboundParam,
|
|
||||||
/// The expanded tree has too many nodes or is deeper than the depth rule.
|
|
||||||
ExpansionLimit,
|
|
||||||
/// The input nests deeper than the expander can recurse. A stack bound, not the depth rule: the depth
|
|
||||||
/// rule is judged on the finished tree and reports ExpansionLimit.
|
|
||||||
TooDeepToResolve,
|
|
||||||
/// A state record held under another schema than the Bind names.
|
|
||||||
BindSchemaMismatch,
|
|
||||||
/// An Image names a catalog or an asset the catalog does not hold.
|
|
||||||
AssetMissing,
|
|
||||||
/// A member path names a member the value does not have.
|
|
||||||
BindMemberMissing,
|
|
||||||
/// A value of another type than its site takes; no value is coerced.
|
|
||||||
BindTypeMismatch,
|
|
||||||
/// Two items of one Repeat share a key.
|
|
||||||
RepeatKeyDuplicate,
|
|
||||||
/// A surface offered at a version at or below one already offered; the held tree stays.
|
|
||||||
StaleVersionIgnored,
|
|
||||||
/// A style slot holding a value its CSS counterpart forbids; the slot took its initial value.
|
|
||||||
StyleValueInvalid,
|
|
||||||
/// A laid node reaches past the precision bound: the layout is refused, never rounded.
|
|
||||||
LayoutOutOfRange,
|
|
||||||
/// An Overlay anchored to a node that is not laid (hidden or absent); it was placed against the viewport.
|
|
||||||
OverlayAnchorMissing,
|
|
||||||
/// A colour or text token the theme does not hold; it drew as the fallback colour.
|
|
||||||
ThemeTokenUnknown,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Code {
|
|
||||||
/// Whether the fault leaves no tree (the whole document is refused) or only a placeholder.
|
|
||||||
pub fn refuses_document(self) -> bool {
|
|
||||||
matches!(self, Code::UndeclaredCommand | Code::DuplicateNodeId | Code::UnboundParam | Code::ExpansionLimit | Code::TooDeepToResolve)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One fault. `detail` names the fault and never carries a state value.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub struct Diagnostic {
|
|
||||||
pub code: Code,
|
|
||||||
/// The record key of the surface the fault is in.
|
|
||||||
pub surface: String,
|
|
||||||
pub node: Option<NodeId>,
|
|
||||||
pub detail: String,
|
|
||||||
}
|
|
||||||
|
|
@ -1,171 +0,0 @@
|
||||||
//! The frame entry: one `Core::frame` call per frame the host makes drains the port, resolves,
|
|
||||||
//! binds, lays out and renders. Core owns the pipeline order and is the only caller of
|
|
||||||
//! `StatePort::drain`; it reads no clock, sleeps nowhere and never awaits. Later cuts extend
|
|
||||||
//! `frame` in place with their own step; there is no second entry.
|
|
||||||
|
|
||||||
use thing_contract::{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(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,83 +0,0 @@
|
||||||
//! The closed input model every host speaks to core. It is not `#[non_exhaustive]`: a new
|
|
||||||
//! variant is a contract revision every host compiles against.
|
|
||||||
//!
|
|
||||||
//! The viewport and the scale are not events: they are `FrameInput` fields, and a resize is the
|
|
||||||
//! next frame's viewport. Time is not an event either (`FrameInput::now`).
|
|
||||||
|
|
||||||
/// One thing the user did, in the order the host saw it.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub enum InputEvent {
|
|
||||||
/// A key press or auto-repeat (`repeat: true`). A release never enters: a terminal
|
|
||||||
/// reports Release on Windows and the TUI drops it, and the web host drops keyup. `Char` is the
|
|
||||||
/// character the keyboard layout produced (Shift+a is `Char('A')` with `shift` set;
|
|
||||||
/// Shift+Tab is `Tab` with `shift`). A typing key emits `Key` then `Text`, in that order (DOM
|
|
||||||
/// keydown precedes beforeinput; a window system's key event carries text beside the key; egui emits
|
|
||||||
/// Event::Key then Event::Text); a Ctrl or Alt chord emits `Key` only. Commands bind to `Key`.
|
|
||||||
Key { key: Key, modifiers: Modifiers, repeat: bool },
|
|
||||||
/// Committed text to insert; a paste is `Text`. Text inserts only from `Text`, so nothing
|
|
||||||
/// inserts twice.
|
|
||||||
Text(String),
|
|
||||||
/// The IME preedit, replacing any earlier one; empty `text` ends it without commit, and the
|
|
||||||
/// commit arrives as `Text` (DOM compositionupdate/compositionend; a window system's IME preedit and commit).
|
|
||||||
/// `cursor` is UTF-8 byte offsets into `text`, the window-system convention; the web host converts the
|
|
||||||
/// DOM's UTF-16 offsets.
|
|
||||||
Compose { text: String, cursor: Option<(u32, u32)> },
|
|
||||||
/// `at` is in the space `Placed` is in: logical px, or cells where a terminal cell
|
|
||||||
/// `(col, row)` is its centre `(col + 0.5, row + 0.5)`, the point the TUI's paint covers a
|
|
||||||
/// cell by, so a hit and a drawn cell agree.
|
|
||||||
PointerDown { at: (f32, f32), button: PointerButton, modifiers: Modifiers },
|
|
||||||
/// Sent with or without a button held.
|
|
||||||
PointerMove { at: (f32, f32), modifiers: Modifiers },
|
|
||||||
PointerUp { at: (f32, f32), button: PointerButton, modifiers: Modifiers },
|
|
||||||
/// The platform took the pointer (DOM pointercancel; the web host uses setPointerCapture so
|
|
||||||
/// an up outside the canvas still arrives): a pending press is dropped and no up follows.
|
|
||||||
PointerCancel,
|
|
||||||
/// `delta` positive y moves content toward its end (the scroll offset grows), positive x
|
|
||||||
/// right: the DOM WheelEvent sign. A terminal's ScrollDown is `(0, 1)` `Lines`; a
|
|
||||||
/// window system whose line delta has the opposite sign is negated by its host. `Units` are logical px or
|
|
||||||
/// cells; `Lines` are converted by core.
|
|
||||||
Wheel { at: (f32, f32), delta: (f32, f32), unit: WheelUnit, modifiers: Modifiers },
|
|
||||||
/// The host window or terminal gained (`true`) or lost focus.
|
|
||||||
Focus(bool),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
|
||||||
pub enum Key {
|
|
||||||
Char(char),
|
|
||||||
Enter,
|
|
||||||
Tab,
|
|
||||||
Backspace,
|
|
||||||
Delete,
|
|
||||||
Escape,
|
|
||||||
Left,
|
|
||||||
Right,
|
|
||||||
Up,
|
|
||||||
Down,
|
|
||||||
Home,
|
|
||||||
End,
|
|
||||||
PageUp,
|
|
||||||
PageDown,
|
|
||||||
Insert,
|
|
||||||
F(u8),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
|
||||||
pub struct Modifiers {
|
|
||||||
pub shift: bool,
|
|
||||||
pub ctrl: bool,
|
|
||||||
pub alt: bool,
|
|
||||||
pub meta: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
|
||||||
pub enum PointerButton {
|
|
||||||
Primary,
|
|
||||||
Secondary,
|
|
||||||
Middle,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
|
||||||
pub enum WheelUnit {
|
|
||||||
Units,
|
|
||||||
Lines,
|
|
||||||
}
|
|
||||||
|
|
@ -1,5 +0,0 @@
|
||||||
//! What a host tells core about its user: the closed `InputEvent` vocabulary.
|
|
||||||
|
|
||||||
pub mod event;
|
|
||||||
|
|
||||||
pub use event::{InputEvent, Key, Modifiers, PointerButton, WheelUnit};
|
|
||||||
|
|
@ -1,189 +0,0 @@
|
||||||
//! The Measure seam: what a leaf's intrinsic size is. Text, controls and images are sized by a
|
|
||||||
//! `Measure` the frame owner composes (cut 9a ships Pixels and Cells); layout never estimates
|
|
||||||
//! them. Taffy's own types stop at this file: `Leaf` and `Constraint` are plain data.
|
|
||||||
|
|
||||||
use taffy::{AvailableSpace, Size};
|
|
||||||
use thing_contract::NodeId;
|
|
||||||
|
|
||||||
use crate::bind::Bound;
|
|
||||||
use 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(()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,216 +0,0 @@
|
||||||
//! Layout: a `BoundTree` and a `LayoutFrame` become the geometry of every node, solved by Taffy
|
|
||||||
//! (the one solver) and handed back as plain rectangles. A pure function: it reads no port, no
|
|
||||||
//! clock and no state, builds a fresh Taffy tree per call and keeps none.
|
|
||||||
//!
|
|
||||||
//! Pixels mode runs the solver in device pixels (every Px length and every measured size is
|
|
||||||
//! multiplied by the scale factor at the one adapter) with Taffy's cumulative rounding, so every
|
|
||||||
//! edge lands on a device pixel and adjacent boxes share it. Cells mode ignores the scale. The
|
|
||||||
//! viewport is a block container the document root flows in, and is not itself in the output.
|
|
||||||
//! Overlays are out of flow: after the main pass each is laid out as its own root against its anchor
|
|
||||||
//! and appended after every main-tree node.
|
|
||||||
|
|
||||||
mod measure;
|
|
||||||
mod overlay;
|
|
||||||
mod style;
|
|
||||||
mod tree;
|
|
||||||
|
|
||||||
use taffy::{AvailableSpace, Size, compute_leaf_layout};
|
|
||||||
use measure::Device;
|
|
||||||
use thing_contract::{NodeId, OverlayNode};
|
|
||||||
|
|
||||||
pub use measure::{Avail, CellStyle, Constraint, FontId, Glyph, Leaf, Measure, Run, TextLayout, TextLine, TextRequest};
|
|
||||||
pub(crate) use measure::MAX_DEVICE;
|
|
||||||
|
|
||||||
use crate::bind::BoundTree;
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
|
|
||||||
/// The stack one level of nesting takes inside Taffy's recursion, worst of Flex, Grid, Block and
|
|
||||||
/// scroll boxes, measured in a debug build by `stack_per_level` in tests/layout.rs, doubled.
|
|
||||||
/// Taffy recurses natively and nothing in it can be wrapped per level, so the walk's depth is
|
|
||||||
/// known first and the one segment is sized for it.
|
|
||||||
const STACK_PER_LEVEL: usize = 96 * 1024;
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub enum Metrics {
|
|
||||||
Pixels,
|
|
||||||
Cells,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The room one layout fills. `viewport` is logical px (Pixels) or cells (Cells); `scale` is the
|
|
||||||
/// device pixels per logical px and is ignored in Cells.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
||||||
pub struct LayoutFrame {
|
|
||||||
pub viewport: (f32, f32),
|
|
||||||
pub scale: f32,
|
|
||||||
pub metrics: Metrics,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
|
||||||
pub struct Rect {
|
|
||||||
pub x: f32,
|
|
||||||
pub y: f32,
|
|
||||||
pub w: f32,
|
|
||||||
pub h: f32,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One node's geometry. `rect` is the absolute border box in device px (Pixels) or cells, and is
|
|
||||||
/// unscrolled. `parent` indexes the nearest laid ancestor in `LaidTree.nodes` (none for the
|
|
||||||
/// document root and every overlay root). `content` is the scrollable content size of an
|
|
||||||
/// `Overflow::Scroll` node; `clip` is the padding box (the border box inset by the laid border)
|
|
||||||
/// of a Clip or Scroll node.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct LaidNode {
|
|
||||||
pub id: NodeId,
|
|
||||||
pub parent: Option<u32>,
|
|
||||||
pub rect: Rect,
|
|
||||||
pub content: Option<(f32, f32)>,
|
|
||||||
/// How far `content` reaches past the padding box, never negative: the furthest the content
|
|
||||||
/// may scroll. Input clamps its position here; render and hit-test translate the children by
|
|
||||||
/// it. Layout never sees a scroll position, so a scroll never re-runs layout.
|
|
||||||
pub max_scroll: Option<(f32, f32)>,
|
|
||||||
pub clip: Option<Rect>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every laid node in paint order (document order, Repeat instances spliced), and the style
|
|
||||||
/// values that were not legal.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct LaidTree {
|
|
||||||
pub nodes: Vec<LaidNode>,
|
|
||||||
pub diagnostics: Vec<Diagnostic>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whole numbers stay whole, and negative zero is written as zero.
|
|
||||||
fn clean(v: f32) -> f32 {
|
|
||||||
if v == 0.0 || !v.is_finite() { 0.0 } else { v }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Why a frame was refused: nothing is laid out in a room that is not a finite positive size.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
|
||||||
pub enum FrameError {
|
|
||||||
/// The scale is not finite, not positive or past 1024 (Pixels only).
|
|
||||||
Scale,
|
|
||||||
/// A viewport side is not finite, not positive or past the length bound.
|
|
||||||
Viewport,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Why no layout came back. The frame owner keeps the last good `LaidTree` on either and shows
|
|
||||||
/// the diagnostic of `OutOfRange` (code `LayoutOutOfRange`, naming the first offending node in
|
|
||||||
/// document order).
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub enum LayoutError {
|
|
||||||
Frame(FrameError),
|
|
||||||
OutOfRange(Diagnostic),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<FrameError> for LayoutError {
|
|
||||||
fn from(error: FrameError) -> Self {
|
|
||||||
LayoutError::Frame(error)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn layout(tree: &BoundTree, frame: &LayoutFrame, measure: &mut dyn Measure) -> Result<LaidTree, LayoutError> {
|
|
||||||
let k = match frame.metrics {
|
|
||||||
Metrics::Cells => 1.0,
|
|
||||||
Metrics::Pixels if frame.scale.is_finite() && frame.scale > 0.0 && frame.scale <= 1024.0 => frame.scale,
|
|
||||||
Metrics::Pixels => return Err(FrameError::Scale.into()),
|
|
||||||
};
|
|
||||||
let dev = Device::new(k, frame.metrics == Metrics::Cells);
|
|
||||||
let side = |v: f32| (v.is_finite() && v > 0.0 && dev.px(v) <= MAX_DEVICE).then(|| dev.px(v));
|
|
||||||
let (Some(vw), Some(vh)) = (side(frame.viewport.0), side(frame.viewport.1)) else {
|
|
||||||
return Err(FrameError::Viewport.into());
|
|
||||||
};
|
|
||||||
let mut nodes = Vec::new();
|
|
||||||
let mut diagnostics = Vec::new();
|
|
||||||
let main = tree::build(tree, dev, tree::Top::Document, (vw, vh), measure);
|
|
||||||
let overlays = solve(tree, main, dev, (vw, vh), (0.0, 0.0), measure, &mut nodes, &mut diagnostics)?;
|
|
||||||
overlay::place_all(tree, dev, (vw, vh), overlays, measure, &mut nodes, &mut diagnostics)?;
|
|
||||||
Ok(LaidTree { nodes, diagnostics })
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Solve one built Taffy tree in `size` device px, its origin at `origin`, and append its laid
|
|
||||||
/// nodes (absolute, in entry order) and its diagnostics. Returns the Overlays the tree met in flow.
|
|
||||||
#[allow(clippy::too_many_arguments)]
|
|
||||||
fn solve<'a>(
|
|
||||||
tree: &BoundTree,
|
|
||||||
mut built: tree::Built<'a>,
|
|
||||||
dev: Device,
|
|
||||||
size: (f32, f32),
|
|
||||||
origin: (f32, f32),
|
|
||||||
measure: &mut dyn Measure,
|
|
||||||
nodes: &mut Vec<LaidNode>,
|
|
||||||
diagnostics: &mut Vec<Diagnostic>,
|
|
||||||
) -> Result<Vec<&'a OverlayNode>, LayoutError> {
|
|
||||||
let tree::Built { taffy, root, entries, leaves, diagnostics: own, overlays } = &mut built;
|
|
||||||
let space = Size { width: AvailableSpace::Definite(size.0), height: AvailableSpace::Definite(size.1) };
|
|
||||||
// Entries come parent first, so one pass finds the deepest; the viewport and a spare few add.
|
|
||||||
let mut depth = vec![1usize; entries.len()];
|
|
||||||
for (i, entry) in entries.iter().enumerate() {
|
|
||||||
depth[i] = entry.parent.map_or(1, |parent| depth[parent] + 1);
|
|
||||||
}
|
|
||||||
let levels = depth.iter().copied().max().unwrap_or(0) + 8;
|
|
||||||
stacker::grow(STACK_PER_LEVEL * levels, || {
|
|
||||||
taffy
|
|
||||||
.compute_layout_with_measure(*root, space, |inputs, _, context, style| {
|
|
||||||
let leaf = context.and_then(|index| leaves.get(*index));
|
|
||||||
compute_leaf_layout(
|
|
||||||
inputs,
|
|
||||||
style,
|
|
||||||
|_, _| 0.0,
|
|
||||||
|known, space| match leaf {
|
|
||||||
Some(leaf) => measure::measure_leaf(measure, leaf, dev, known, space),
|
|
||||||
None => Size::ZERO,
|
|
||||||
},
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.expect("taffy: the root is in the tree")
|
|
||||||
});
|
|
||||||
let base = nodes.len();
|
|
||||||
let mut absolute: Vec<(f32, f32)> = Vec::with_capacity(entries.len());
|
|
||||||
for entry in entries.iter() {
|
|
||||||
let laid = taffy.layout(entry.node).expect("taffy: node is in the tree");
|
|
||||||
let (px, py) = entry.parent.map_or(origin, |parent| absolute[parent]);
|
|
||||||
let (x, y) = (px + laid.location.x, py + laid.location.y);
|
|
||||||
absolute.push((x, y));
|
|
||||||
let (w, h) = (laid.size.width, laid.size.height);
|
|
||||||
// Taffy's content extent is measured from the padding box. `content` is never smaller than
|
|
||||||
// the border box; `max_scroll` is what the content reaches past the padding box.
|
|
||||||
let reached = entry.scroll.then(|| {
|
|
||||||
let overflow = laid.scrollable_overflow_rect.rect();
|
|
||||||
let round = |v: f32| (v + 0.5).floor();
|
|
||||||
(round(overflow.right), round(overflow.bottom))
|
|
||||||
});
|
|
||||||
let content = reached.map(|(cw, ch)| (clean(cw.max(w)), clean(ch.max(h))));
|
|
||||||
let max_scroll = reached.map(|(cw, ch)| {
|
|
||||||
let inner_w = w - laid.border.left - laid.border.right;
|
|
||||||
let inner_h = h - laid.border.top - laid.border.bottom;
|
|
||||||
(clean((cw - inner_w).max(0.0)), clean((ch - inner_h).max(0.0)))
|
|
||||||
});
|
|
||||||
// Precision is a property of the whole layout: a position or an extent past the bound
|
|
||||||
// (a sum along an axis included) refuses it, so no value is silently rounded.
|
|
||||||
let reach = [x, y, x + w, y + h, content.map_or(0.0, |c| c.0), content.map_or(0.0, |c| c.1)];
|
|
||||||
if reach.iter().any(|v| !v.is_finite() || v.abs() > MAX_DEVICE) {
|
|
||||||
return Err(LayoutError::OutOfRange(Diagnostic {
|
|
||||||
code: Code::LayoutOutOfRange,
|
|
||||||
surface: tree.resolved().document().record_key(),
|
|
||||||
node: Some(entry.id.clone()),
|
|
||||||
detail: "position or extent past the precision bound".to_string(),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
let clip = entry.clip.then(|| Rect {
|
|
||||||
x: clean(x + laid.border.left),
|
|
||||||
y: clean(y + laid.border.top),
|
|
||||||
w: clean(w - laid.border.left - laid.border.right),
|
|
||||||
h: clean(h - laid.border.top - laid.border.bottom),
|
|
||||||
});
|
|
||||||
nodes.push(LaidNode {
|
|
||||||
id: entry.id.clone(),
|
|
||||||
parent: entry.parent.map(|parent| (base + parent) as u32),
|
|
||||||
rect: Rect { x: clean(x), y: clean(y), w: clean(w), h: clean(h) },
|
|
||||||
content,
|
|
||||||
max_scroll,
|
|
||||||
clip,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
diagnostics.append(own);
|
|
||||||
Ok(std::mem::take(overlays))
|
|
||||||
}
|
|
||||||
|
|
@ -1,56 +0,0 @@
|
||||||
//! The overlay pass: each Overlay is its own Taffy root, laid out against its anchor after the
|
|
||||||
//! main pass and appended after every main-tree node, which is the paint order (overlays last).
|
|
||||||
//! The viewport and a node anchor share one placement: the anchor's rect is the overlay's origin
|
|
||||||
//! and size.
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
use thing_contract::{Anchor, NodeId, OverlayNode};
|
|
||||||
|
|
||||||
use super::measure::Device;
|
|
||||||
use super::tree::{self, Top};
|
|
||||||
use super::{LaidNode, LayoutError, Measure, Rect, solve};
|
|
||||||
use crate::bind::BoundTree;
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
|
|
||||||
/// Lay out `first` and every Overlay nested in them: each Overlay before the Overlays inside it,
|
|
||||||
/// in document order, so an anchor inside an earlier Overlay resolves. An anchor that is not laid
|
|
||||||
/// (hidden, absent) places the overlay against the viewport and is named once.
|
|
||||||
pub(super) fn place_all<'a>(
|
|
||||||
tree: &'a BoundTree,
|
|
||||||
dev: Device,
|
|
||||||
viewport: (f32, f32),
|
|
||||||
first: Vec<&'a OverlayNode>,
|
|
||||||
measure: &mut dyn Measure,
|
|
||||||
nodes: &mut Vec<LaidNode>,
|
|
||||||
diagnostics: &mut Vec<Diagnostic>,
|
|
||||||
) -> Result<(), LayoutError> {
|
|
||||||
let mut rects: HashMap<NodeId, Rect> = nodes.iter().map(|n| (n.id.clone(), n.rect)).collect();
|
|
||||||
let mut pending: Vec<&OverlayNode> = first;
|
|
||||||
pending.reverse();
|
|
||||||
while let Some(overlay) = pending.pop() {
|
|
||||||
let anchor = match &overlay.anchor {
|
|
||||||
Anchor::Viewport => Rect { x: 0.0, y: 0.0, w: viewport.0, h: viewport.1 },
|
|
||||||
Anchor::Node(anchor) => match rects.get(&anchor.node) {
|
|
||||||
Some(rect) => *rect,
|
|
||||||
None => {
|
|
||||||
diagnostics.push(Diagnostic {
|
|
||||||
code: Code::OverlayAnchorMissing,
|
|
||||||
surface: tree.resolved().document().record_key(),
|
|
||||||
node: Some(overlay.common.id.clone()),
|
|
||||||
detail: anchor.node.as_str().to_string(),
|
|
||||||
});
|
|
||||||
Rect { x: 0.0, y: 0.0, w: viewport.0, h: viewport.1 }
|
|
||||||
}
|
|
||||||
},
|
|
||||||
};
|
|
||||||
let built = tree::build(tree, dev, Top::Overlay(overlay), (anchor.w, anchor.h), measure);
|
|
||||||
let start = nodes.len();
|
|
||||||
let nested = solve(tree, built, dev, (anchor.w, anchor.h), (anchor.x, anchor.y), measure, nodes, diagnostics)?;
|
|
||||||
for node in &nodes[start..] {
|
|
||||||
rects.entry(node.id.clone()).or_insert(node.rect);
|
|
||||||
}
|
|
||||||
pending.extend(nested.into_iter().rev());
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
@ -1,289 +0,0 @@
|
||||||
//! The one style map: `BoxStyle` and `Paint` onto Taffy's `Style`. The destructure names every
|
|
||||||
//! contract field, so a new field fails to compile until it is mapped.
|
|
||||||
//!
|
|
||||||
//! A slot holding a value its CSS counterpart forbids (a non-finite or oversized number, a
|
|
||||||
//! negative where none is allowed, a Dimension arm the slot cannot take) takes its initial value
|
|
||||||
//! and is reported once by field name. `Percent` is authored in percent points (50 is half).
|
|
||||||
|
|
||||||
use taffy::style_helpers::TaffyZero;
|
|
||||||
use taffy::{
|
|
||||||
AlignContent, AlignItems, Dimension, Display as TDisplay, FlexDirection, FlexWrap, GridTemplateComponent,
|
|
||||||
LengthPercentage, LengthPercentageAuto, MaxTrackSizingFunction, MinTrackSizingFunction, Overflow as TOverflow,
|
|
||||||
Point, Position as TPosition, Rect, Size, Style, TrackSizingFunction,
|
|
||||||
};
|
|
||||||
use thing_contract as c;
|
|
||||||
|
|
||||||
use super::measure::{Device, MAX_DEVICE};
|
|
||||||
|
|
||||||
/// Field names of the slots that took their initial value.
|
|
||||||
pub(super) type Invalid = Vec<&'static str>;
|
|
||||||
|
|
||||||
fn number(value: f64, negative: bool) -> Option<f32> {
|
|
||||||
let fits = value.is_finite() && value.abs() <= f64::from(MAX_DEVICE) && (negative || value >= 0.0);
|
|
||||||
fits.then_some(value as f32)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn length(scalar: &c::Scalar, dev: Device, negative: bool) -> Option<f32> {
|
|
||||||
number(scalar.value, negative).map(|v| dev.px(v)).filter(|v| v.abs() <= MAX_DEVICE)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn percent(scalar: &c::Scalar, negative: bool) -> Option<f32> {
|
|
||||||
number(scalar.value, negative).map(|v| v / 100.0)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn lp(d: &c::Dimension, dev: Device) -> Option<LengthPercentage> {
|
|
||||||
match d {
|
|
||||||
c::Dimension::Px(s) => length(s, dev, false).map(LengthPercentage::length),
|
|
||||||
c::Dimension::Percent(s) => percent(s, false).map(LengthPercentage::percent),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn lpa(d: &c::Dimension, dev: Device, negative: bool) -> Option<LengthPercentageAuto> {
|
|
||||||
match d {
|
|
||||||
c::Dimension::Px(s) => length(s, dev, negative).map(LengthPercentageAuto::length),
|
|
||||||
c::Dimension::Percent(s) => percent(s, negative).map(LengthPercentageAuto::percent),
|
|
||||||
c::Dimension::Auto => Some(LengthPercentageAuto::auto()),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn size_dim(d: &c::Dimension, dev: Device) -> Option<Dimension> {
|
|
||||||
match d {
|
|
||||||
c::Dimension::Px(s) => length(s, dev, false).map(Dimension::length),
|
|
||||||
c::Dimension::Percent(s) => percent(s, false).map(Dimension::percent),
|
|
||||||
c::Dimension::Auto => Some(Dimension::auto()),
|
|
||||||
c::Dimension::Content => Some(Dimension::fit_content()),
|
|
||||||
c::Dimension::Fr(_) => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn basis_dim(d: &c::Dimension, dev: Device) -> Option<Dimension> {
|
|
||||||
match d {
|
|
||||||
c::Dimension::Content => Some(Dimension::content()),
|
|
||||||
c::Dimension::Fr(_) => None,
|
|
||||||
other => size_dim(other, dev),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn track(d: &c::Dimension, dev: Device) -> Option<GridTemplateComponent<String>> {
|
|
||||||
use MaxTrackSizingFunction as Max;
|
|
||||||
use MinTrackSizingFunction as Min;
|
|
||||||
let (min, max) = match d {
|
|
||||||
c::Dimension::Px(s) => {
|
|
||||||
let v = length(s, dev, false)?;
|
|
||||||
(Min::length(v), Max::length(v))
|
|
||||||
}
|
|
||||||
c::Dimension::Percent(s) => {
|
|
||||||
let v = percent(s, false)?;
|
|
||||||
(Min::percent(v), Max::percent(v))
|
|
||||||
}
|
|
||||||
c::Dimension::Fr(s) => (Min::auto(), Max::fr(number(s.value, false)?)),
|
|
||||||
c::Dimension::Auto => (Min::auto(), Max::auto()),
|
|
||||||
c::Dimension::Content => (Min::max_content(), Max::max_content()),
|
|
||||||
};
|
|
||||||
Some(GridTemplateComponent::Single(TrackSizingFunction { min, max }))
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Slots {
|
|
||||||
dev: Device,
|
|
||||||
invalid: Invalid,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Slots {
|
|
||||||
fn take<T>(&mut self, field: &'static str, value: Option<T>, initial: T) -> T {
|
|
||||||
value.unwrap_or_else(|| {
|
|
||||||
if !self.invalid.contains(&field) {
|
|
||||||
self.invalid.push(field);
|
|
||||||
}
|
|
||||||
initial
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn size2(&mut self, field: &'static str, s: &c::Size2) -> Size<Dimension> {
|
|
||||||
let dev = self.dev;
|
|
||||||
Size {
|
|
||||||
width: self.take(field, size_dim(&s.width, dev), Dimension::auto()),
|
|
||||||
height: self.take(field, size_dim(&s.height, dev), Dimension::auto()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn size2_lpa(&mut self, field: &'static str, s: &c::Size2) -> Size<LengthPercentageAuto> {
|
|
||||||
let dev = self.dev;
|
|
||||||
Size {
|
|
||||||
width: self.take(field, lpa(&s.width, dev, false), LengthPercentageAuto::auto()),
|
|
||||||
height: self.take(field, lpa(&s.height, dev, false), LengthPercentageAuto::auto()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn edges_lpa(
|
|
||||||
&mut self,
|
|
||||||
field: &'static str,
|
|
||||||
e: &c::Edges,
|
|
||||||
negative: bool,
|
|
||||||
initial: LengthPercentageAuto,
|
|
||||||
) -> Rect<LengthPercentageAuto> {
|
|
||||||
let dev = self.dev;
|
|
||||||
Rect {
|
|
||||||
left: self.take(field, lpa(&e.left, dev, negative), initial),
|
|
||||||
right: self.take(field, lpa(&e.right, dev, negative), initial),
|
|
||||||
top: self.take(field, lpa(&e.top, dev, negative), initial),
|
|
||||||
bottom: self.take(field, lpa(&e.bottom, dev, negative), initial),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn edges_lp(&mut self, field: &'static str, e: &c::Edges) -> Rect<LengthPercentage> {
|
|
||||||
let dev = self.dev;
|
|
||||||
let zero = LengthPercentage::ZERO;
|
|
||||||
Rect {
|
|
||||||
left: self.take(field, lp(&e.left, dev), zero),
|
|
||||||
right: self.take(field, lp(&e.right, dev), zero),
|
|
||||||
top: self.take(field, lp(&e.top, dev), zero),
|
|
||||||
bottom: self.take(field, lp(&e.bottom, dev), zero),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn tracks(&mut self, field: &'static str, dims: &[c::Dimension]) -> Vec<GridTemplateComponent<String>> {
|
|
||||||
let dev = self.dev;
|
|
||||||
let tracks: Option<Vec<_>> = dims.iter().map(|d| track(d, dev)).collect();
|
|
||||||
self.take(field, tracks, Vec::new())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn weight(&mut self, field: &'static str, value: f64, initial: f32) -> f32 {
|
|
||||||
self.take(field, number(value, false), initial)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn item(align: &c::ItemAlign) -> Option<AlignItems> {
|
|
||||||
Some(match align {
|
|
||||||
c::ItemAlign::Auto => return None,
|
|
||||||
c::ItemAlign::Start => AlignItems::FLEX_START,
|
|
||||||
c::ItemAlign::End => AlignItems::FLEX_END,
|
|
||||||
c::ItemAlign::Center => AlignItems::CENTER,
|
|
||||||
c::ItemAlign::Stretch => AlignItems::STRETCH,
|
|
||||||
c::ItemAlign::Baseline => AlignItems::BASELINE,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn content(align: &c::ContentAlign, auto: AlignContent) -> AlignContent {
|
|
||||||
match align {
|
|
||||||
c::ContentAlign::Auto => auto,
|
|
||||||
c::ContentAlign::Start => AlignContent::FLEX_START,
|
|
||||||
c::ContentAlign::End => AlignContent::FLEX_END,
|
|
||||||
c::ContentAlign::Center => AlignContent::CENTER,
|
|
||||||
c::ContentAlign::Stretch => AlignContent::STRETCH,
|
|
||||||
c::ContentAlign::SpaceBetween => AlignContent::SPACE_BETWEEN,
|
|
||||||
c::ContentAlign::SpaceAround => AlignContent::SPACE_AROUND,
|
|
||||||
c::ContentAlign::SpaceEvenly => AlignContent::SPACE_EVENLY,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The Taffy style of a Box. `dev` converts Px lengths to the solver's device units; the slots that were not legal are named in the second value.
|
|
||||||
pub(super) fn box_style(s: &c::BoxStyle, paint: &c::Paint, dev: Device) -> (Style, Invalid) {
|
|
||||||
let c::BoxStyle {
|
|
||||||
display,
|
|
||||||
direction,
|
|
||||||
wrap,
|
|
||||||
gap,
|
|
||||||
padding,
|
|
||||||
margin,
|
|
||||||
size,
|
|
||||||
min_size,
|
|
||||||
max_size,
|
|
||||||
position,
|
|
||||||
inset,
|
|
||||||
overflow,
|
|
||||||
align_items,
|
|
||||||
align_self,
|
|
||||||
align_content,
|
|
||||||
justify_content,
|
|
||||||
grow,
|
|
||||||
shrink,
|
|
||||||
basis,
|
|
||||||
grid_columns,
|
|
||||||
grid_rows,
|
|
||||||
} = s;
|
|
||||||
let mut slots = Slots { dev, invalid: Vec::new() };
|
|
||||||
let border = match &paint.border {
|
|
||||||
None => LengthPercentage::ZERO,
|
|
||||||
Some(b) => {
|
|
||||||
let width = slots.take("border", length(&c::Scalar { value: b.width }, dev, false), 0.0);
|
|
||||||
LengthPercentage::length(width)
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let overflow = match overflow {
|
|
||||||
c::Overflow::Visible => TOverflow::Visible,
|
|
||||||
c::Overflow::Clip => TOverflow::Clip,
|
|
||||||
c::Overflow::Scroll => TOverflow::Scroll,
|
|
||||||
};
|
|
||||||
let gap = {
|
|
||||||
let width = slots.take("gap", lp(&gap.width, dev), LengthPercentage::ZERO);
|
|
||||||
let height = slots.take("gap", lp(&gap.height, dev), LengthPercentage::ZERO);
|
|
||||||
Size { width, height }
|
|
||||||
};
|
|
||||||
let style = Style {
|
|
||||||
display: match display {
|
|
||||||
c::Display::Flex => TDisplay::Flex,
|
|
||||||
c::Display::Grid => TDisplay::Grid,
|
|
||||||
c::Display::Block => TDisplay::Block,
|
|
||||||
},
|
|
||||||
flex_direction: match direction {
|
|
||||||
c::Direction::Row => FlexDirection::Row,
|
|
||||||
c::Direction::Column => FlexDirection::Column,
|
|
||||||
c::Direction::RowReverse => FlexDirection::RowReverse,
|
|
||||||
c::Direction::ColumnReverse => FlexDirection::ColumnReverse,
|
|
||||||
},
|
|
||||||
flex_wrap: match wrap {
|
|
||||||
c::Wrap::NoWrap => FlexWrap::NoWrap,
|
|
||||||
c::Wrap::Wrap => FlexWrap::Wrap,
|
|
||||||
c::Wrap::WrapReverse => FlexWrap::WrapReverse,
|
|
||||||
},
|
|
||||||
gap,
|
|
||||||
padding: slots.edges_lp("padding", padding),
|
|
||||||
border: Rect { left: border, right: border, top: border, bottom: border },
|
|
||||||
margin: slots.edges_lpa("margin", margin, true, LengthPercentageAuto::ZERO),
|
|
||||||
size: slots.size2("size", size),
|
|
||||||
min_size: slots.size2_lpa("min_size", min_size),
|
|
||||||
max_size: slots.size2_lpa("max_size", max_size),
|
|
||||||
position: match position {
|
|
||||||
c::Position::Relative => TPosition::Relative,
|
|
||||||
c::Position::Absolute => TPosition::Absolute,
|
|
||||||
},
|
|
||||||
inset: slots.edges_lpa("inset", inset, true, LengthPercentageAuto::auto()),
|
|
||||||
overflow: Point { x: overflow, y: overflow },
|
|
||||||
scrollbar_width: 0.0,
|
|
||||||
align_items: item(align_items).unwrap_or(AlignItems::STRETCH),
|
|
||||||
align_self: item(align_self),
|
|
||||||
align_content: content(align_content, AlignContent::STRETCH),
|
|
||||||
justify_content: content(justify_content, AlignContent::FLEX_START),
|
|
||||||
flex_grow: slots.weight("grow", *grow, 0.0),
|
|
||||||
flex_shrink: slots.weight("shrink", *shrink, 1.0),
|
|
||||||
flex_basis: {
|
|
||||||
let basis = basis_dim(basis, dev);
|
|
||||||
slots.take("basis", basis, Dimension::auto())
|
|
||||||
},
|
|
||||||
grid_template_columns: slots.tracks("grid_columns", grid_columns).into_iter().collect(),
|
|
||||||
grid_template_rows: slots.tracks("grid_rows", grid_rows).into_iter().collect(),
|
|
||||||
..Style::default()
|
|
||||||
};
|
|
||||||
(style, slots.invalid)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An Embed's style: exactly its declared size, never shrunk.
|
|
||||||
pub(super) fn embed_style(width: f64, height: f64, dev: Device) -> (Style, Invalid) {
|
|
||||||
let mut slots = Slots { dev, invalid: Vec::new() };
|
|
||||||
let side = |slots: &mut Slots, value: f64| {
|
|
||||||
let v = slots.take("size", length(&c::Scalar { value }, dev, false), 0.0);
|
|
||||||
(Dimension::length(v), LengthPercentageAuto::length(v))
|
|
||||||
};
|
|
||||||
let (w, wa) = side(&mut slots, width);
|
|
||||||
let (h, ha) = side(&mut slots, height);
|
|
||||||
let style = Style {
|
|
||||||
size: Size { width: w, height: h },
|
|
||||||
min_size: Size { width: wa, height: ha },
|
|
||||||
max_size: Size { width: wa, height: ha },
|
|
||||||
flex_shrink: 0.0,
|
|
||||||
..Style::default()
|
|
||||||
};
|
|
||||||
(style, slots.invalid)
|
|
||||||
}
|
|
||||||
|
|
@ -1,295 +0,0 @@
|
||||||
//! The walk: a `BoundTree` becomes a Taffy tree, one Taffy node per laid node, Repeats spliced.
|
|
||||||
|
|
||||||
use taffy::{Style, TaffyTree};
|
|
||||||
use thing_contract::{Node, NodeId, Overflow, OverlayNode};
|
|
||||||
|
|
||||||
use super::measure::{Device, Leaf, MAX_DEVICE, intrinsic_ratio};
|
|
||||||
use super::style::{Invalid, box_style, embed_style};
|
|
||||||
use crate::bind::{Bound, BoundTree, Field};
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
use crate::resolve::grow;
|
|
||||||
|
|
||||||
static ABSENT: Bound = Bound::Absent;
|
|
||||||
|
|
||||||
/// One laid node, in document order. `parent` is the entry of the nearest laid ancestor.
|
|
||||||
pub(super) struct Entry<'a> {
|
|
||||||
pub(super) id: &'a NodeId,
|
|
||||||
pub(super) node: taffy::NodeId,
|
|
||||||
pub(super) parent: Option<usize>,
|
|
||||||
pub(super) clip: bool,
|
|
||||||
pub(super) scroll: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) struct Built<'a> {
|
|
||||||
pub(super) taffy: TaffyTree<usize>,
|
|
||||||
pub(super) root: taffy::NodeId,
|
|
||||||
pub(super) entries: Vec<Entry<'a>>,
|
|
||||||
/// The Taffy context of a measured leaf is its index here.
|
|
||||||
pub(super) leaves: Vec<Leaf<'a>>,
|
|
||||||
pub(super) diagnostics: Vec<Diagnostic>,
|
|
||||||
/// The visible Overlays met in flow, in document order, for the overlay pass.
|
|
||||||
pub(super) overlays: Vec<&'a OverlayNode>,
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Builder<'a, 'm> {
|
|
||||||
tree: &'a BoundTree,
|
|
||||||
surface: String,
|
|
||||||
dev: Device,
|
|
||||||
measure: &'m mut dyn super::Measure,
|
|
||||||
taffy: TaffyTree<usize>,
|
|
||||||
entries: Vec<Entry<'a>>,
|
|
||||||
leaves: Vec<Leaf<'a>>,
|
|
||||||
diagnostics: Vec<Diagnostic>,
|
|
||||||
overlays: Vec<&'a OverlayNode>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What the Taffy tree is rooted at: the viewport holding the document root, or one Overlay.
|
|
||||||
pub(super) enum Top<'a> {
|
|
||||||
Document,
|
|
||||||
Overlay(&'a OverlayNode),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Build one Taffy tree of `size` device px. The document's tree is a block container (the
|
|
||||||
/// viewport) the root flows in, so a root with an auto width fills it and a Repeat at the root has
|
|
||||||
/// a parent to splice into. An Overlay's tree is the Overlay itself, the first entry: a container
|
|
||||||
/// of Taffy's default style the anchor's size, so its children are laid against the anchor.
|
|
||||||
pub(super) fn build<'a>(
|
|
||||||
tree: &'a BoundTree,
|
|
||||||
dev: Device,
|
|
||||||
top: Top<'a>,
|
|
||||||
size: (f32, f32),
|
|
||||||
measure: &mut dyn super::Measure,
|
|
||||||
) -> Built<'a> {
|
|
||||||
let document = tree.resolved().document();
|
|
||||||
let mut builder = Builder {
|
|
||||||
tree,
|
|
||||||
surface: document.record_key(),
|
|
||||||
dev,
|
|
||||||
measure,
|
|
||||||
taffy: TaffyTree::new(),
|
|
||||||
entries: Vec::new(),
|
|
||||||
leaves: Vec::new(),
|
|
||||||
diagnostics: Vec::new(),
|
|
||||||
overlays: Vec::new(),
|
|
||||||
};
|
|
||||||
let mut kids = Vec::new();
|
|
||||||
let mut style = Style {
|
|
||||||
size: taffy::Size { width: taffy::Dimension::length(size.0), height: taffy::Dimension::length(size.1) },
|
|
||||||
..Style::default()
|
|
||||||
};
|
|
||||||
let overlay = match top {
|
|
||||||
Top::Document => {
|
|
||||||
builder.visit(&document.root, None, &mut kids);
|
|
||||||
style.display = taffy::Display::Block;
|
|
||||||
style.position = taffy::Position::Relative;
|
|
||||||
None
|
|
||||||
}
|
|
||||||
Top::Overlay(overlay) => {
|
|
||||||
let index = builder.entry(&overlay.common.id, None, &Overflow::Visible);
|
|
||||||
for child in &overlay.children {
|
|
||||||
builder.visit(child, Some(index), &mut kids);
|
|
||||||
}
|
|
||||||
Some(index)
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let root = builder.taffy.new_with_children(style, &kids).expect("taffy: insert");
|
|
||||||
if let Some(index) = overlay {
|
|
||||||
builder.entries[index].node = root;
|
|
||||||
}
|
|
||||||
Built {
|
|
||||||
taffy: builder.taffy,
|
|
||||||
root,
|
|
||||||
entries: builder.entries,
|
|
||||||
leaves: builder.leaves,
|
|
||||||
diagnostics: builder.diagnostics,
|
|
||||||
overlays: builder.overlays,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> Builder<'a, '_> {
|
|
||||||
fn hidden(&self, id: &NodeId) -> bool {
|
|
||||||
matches!(self.tree.value(id, Field::Visible), Some(Bound::Bool(false)))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn value(&self, id: &NodeId, field: Field) -> &'a Bound {
|
|
||||||
self.tree.value(id, field).unwrap_or(&ABSENT)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn report(&mut self, id: &NodeId, invalid: Invalid) {
|
|
||||||
for field in invalid {
|
|
||||||
self.diagnostics.push(Diagnostic {
|
|
||||||
code: Code::StyleValueInvalid,
|
|
||||||
surface: self.surface.clone(),
|
|
||||||
node: Some(id.clone()),
|
|
||||||
detail: field.to_string(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn entry(&mut self, id: &'a NodeId, parent: Option<usize>, overflow: &Overflow) -> usize {
|
|
||||||
let clip = !matches!(overflow, Overflow::Visible);
|
|
||||||
let scroll = matches!(overflow, Overflow::Scroll);
|
|
||||||
self.entries.push(Entry { id, node: taffy::NodeId::from(0u64), parent, clip, scroll });
|
|
||||||
self.entries.len() - 1
|
|
||||||
}
|
|
||||||
|
|
||||||
fn leaf(&mut self, id: &'a NodeId, parent: Option<usize>, leaf: Leaf<'a>, out: &mut Vec<taffy::NodeId>) {
|
|
||||||
let mut style = Style::default();
|
|
||||||
if matches!(leaf, Leaf::Image { .. }) {
|
|
||||||
// A stretched image keeps its shape: the ratio is what the measure says it is unconstrained.
|
|
||||||
// Whatever its ratio derives, a side of the image stays within the length bound.
|
|
||||||
let bound = taffy::LengthPercentageAuto::length(MAX_DEVICE);
|
|
||||||
style.max_size = taffy::Size { width: bound, height: bound };
|
|
||||||
// An invalid measure leaves the image unconstrained (no ratio, not replaced) and is named.
|
|
||||||
match intrinsic_ratio(self.measure, &leaf, self.dev) {
|
|
||||||
Ok(ratio) => {
|
|
||||||
style.item_is_replaced = true;
|
|
||||||
style.aspect_ratio = ratio;
|
|
||||||
}
|
|
||||||
Err(()) => self.report(id, vec!["measure"]),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let index = self.entry(id, parent, &Overflow::Visible);
|
|
||||||
let context = self.leaves.len();
|
|
||||||
self.leaves.push(leaf);
|
|
||||||
let node = self.taffy.new_leaf_with_context(style, context).expect("taffy: insert");
|
|
||||||
self.entries[index].node = node;
|
|
||||||
out.push(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn container(
|
|
||||||
&mut self,
|
|
||||||
id: &'a NodeId,
|
|
||||||
parent: Option<usize>,
|
|
||||||
(style, invalid): (Style, Invalid),
|
|
||||||
overflow: &Overflow,
|
|
||||||
children: &'a [Node],
|
|
||||||
out: &mut Vec<taffy::NodeId>,
|
|
||||||
) {
|
|
||||||
self.report(id, invalid);
|
|
||||||
let index = self.entry(id, parent, overflow);
|
|
||||||
let mut kids = Vec::new();
|
|
||||||
for child in children {
|
|
||||||
self.visit(child, Some(index), &mut kids);
|
|
||||||
}
|
|
||||||
let node = self.taffy.new_with_children(style, &kids).expect("taffy: insert");
|
|
||||||
self.entries[index].node = node;
|
|
||||||
out.push(node);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Append the Taffy nodes `node` contributes to its parent's children: one, none (hidden,
|
|
||||||
/// Overlay, a Repeat with no instances) or one per Repeat instance.
|
|
||||||
fn visit(&mut self, node: &'a Node, parent: Option<usize>, out: &mut Vec<taffy::NodeId>) {
|
|
||||||
grow(|| match node {
|
|
||||||
Node::Box(b) => {
|
|
||||||
if !self.hidden(&b.common.id) {
|
|
||||||
let style = box_style(&b.style, &b.paint, self.dev);
|
|
||||||
self.container(&b.common.id, parent, style, &b.style.overflow, &b.children, out);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Node::Button(b) => {
|
|
||||||
if !self.hidden(&b.common.id) {
|
|
||||||
self.container(&b.common.id, parent, (Style::default(), Vec::new()), &Overflow::Visible, &b.content, out);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// A Repeat has no box: its instances are its parent's children, in instance order.
|
|
||||||
Node::Repeat(r) => {
|
|
||||||
if !self.hidden(&r.common.id) {
|
|
||||||
for instance in self.tree.instances(&r.common.id) {
|
|
||||||
self.visit(&instance.root, parent, out);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// An Overlay is out of flow: nothing here; the overlay pass lays it out against its anchor.
|
|
||||||
Node::Overlay(o) => {
|
|
||||||
if !self.hidden(&o.common.id) {
|
|
||||||
self.overlays.push(o);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// A Use that stayed is resolve's placeholder (beside its diagnostic): a childless leaf
|
|
||||||
// that keeps its place so render can draw the error. A Slot never survives resolve.
|
|
||||||
Node::Use(u) => {
|
|
||||||
if !self.hidden(&u.common.id) {
|
|
||||||
let index = self.entry(&u.common.id, parent, &Overflow::Visible);
|
|
||||||
let least = taffy::LengthPercentageAuto::length(self.dev.placeholder());
|
|
||||||
let style = Style { min_size: taffy::Size { width: least, height: least }, ..Style::default() };
|
|
||||||
let id = self.taffy.new_leaf(style).expect("taffy: insert");
|
|
||||||
self.entries[index].node = id;
|
|
||||||
out.push(id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Node::Slot(_) => debug_assert!(false, "resolve expands Slot"),
|
|
||||||
Node::Embed(e) => {
|
|
||||||
if !self.hidden(&e.common.id) {
|
|
||||||
let (style, invalid) = embed_style(e.width, e.height, self.dev);
|
|
||||||
self.report(&e.common.id, invalid);
|
|
||||||
let index = self.entry(&e.common.id, parent, &Overflow::Visible);
|
|
||||||
let id = self.taffy.new_leaf(style).expect("taffy: insert");
|
|
||||||
self.entries[index].node = id;
|
|
||||||
out.push(id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Node::Text(n) => {
|
|
||||||
let id = &n.common.id;
|
|
||||||
if !self.hidden(id) {
|
|
||||||
let leaf = Leaf::Text {
|
|
||||||
node: id,
|
|
||||||
content: self.value(id, Field::Content),
|
|
||||||
style_token: &n.style_token,
|
|
||||||
wrap: n.wrap,
|
|
||||||
max_lines: n.max_lines.map(|lines| lines.get().max(0) as u32),
|
|
||||||
};
|
|
||||||
self.leaf(id, parent, leaf, out);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Node::TextInput(n) => {
|
|
||||||
let id = &n.common.id;
|
|
||||||
if !self.hidden(id) {
|
|
||||||
let leaf = Leaf::TextInput {
|
|
||||||
node: id,
|
|
||||||
multiline: n.multiline,
|
|
||||||
placeholder: self.value(id, Field::Placeholder),
|
|
||||||
value: self.value(id, Field::Initial),
|
|
||||||
};
|
|
||||||
self.leaf(id, parent, leaf, out);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Node::Toggle(n) => {
|
|
||||||
if !self.hidden(&n.common.id) {
|
|
||||||
self.leaf(&n.common.id, parent, Leaf::Toggle { node: &n.common.id }, out);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Node::Slider(n) => {
|
|
||||||
if !self.hidden(&n.common.id) {
|
|
||||||
self.leaf(&n.common.id, parent, Leaf::Slider { node: &n.common.id }, out);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Node::Select(n) => {
|
|
||||||
let id = &n.common.id;
|
|
||||||
if !self.hidden(id) {
|
|
||||||
self.leaf(id, parent, Leaf::Select { node: id, selected: self.value(id, Field::Selected) }, out);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Node::Image(n) => {
|
|
||||||
if !self.hidden(&n.common.id) {
|
|
||||||
let leaf = Leaf::Image { node: &n.common.id, asset: self.value(&n.common.id, Field::Asset) };
|
|
||||||
self.leaf(&n.common.id, parent, leaf, out);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Node::Plot(n) => {
|
|
||||||
if !self.hidden(&n.common.id) {
|
|
||||||
// A plot declares no size: layout gives it the default object size.
|
|
||||||
let (width, height) = self.dev.plot();
|
|
||||||
let style = Style {
|
|
||||||
size: taffy::Size { width: taffy::Dimension::length(width), height: taffy::Dimension::length(height) },
|
|
||||||
..Style::default()
|
|
||||||
};
|
|
||||||
let index = self.entry(&n.common.id, parent, &Overflow::Visible);
|
|
||||||
let id = self.taffy.new_leaf(style).expect("taffy: insert");
|
|
||||||
self.entries[index].node = id;
|
|
||||||
out.push(id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
//! Thing's core: a function of documents, state, input and time. It touches the world only
|
|
||||||
//! through ports; it reads no clock, spawns nothing and awaits nothing.
|
|
||||||
|
|
||||||
pub mod bind;
|
|
||||||
pub mod diagnostic;
|
|
||||||
pub mod frame;
|
|
||||||
pub mod input;
|
|
||||||
pub mod layout;
|
|
||||||
pub mod port;
|
|
||||||
pub mod render;
|
|
||||||
pub mod resolve;
|
|
||||||
pub mod text;
|
|
||||||
pub mod theme;
|
|
||||||
pub mod time;
|
|
||||||
|
|
||||||
pub use frame::{Config, Core, FrameInput, FrameOutput, Ports};
|
|
||||||
|
|
@ -1,53 +0,0 @@
|
||||||
//! The one interest ledger: core holds a state interest once however many readers ask for it. A
|
|
||||||
//! reader (the Resolver or the Binder) holds and releases through the ledger, never through the
|
|
||||||
//! port, so one `SubscriptionId` per interest is shared by count and an interest nothing reads
|
|
||||||
//! is unsubscribed.
|
|
||||||
|
|
||||||
use std::collections::{HashMap, HashSet};
|
|
||||||
|
|
||||||
use super::{Interest, StatePort, SubscriptionId};
|
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
|
||||||
pub struct Ledger {
|
|
||||||
held: HashMap<Interest, (SubscriptionId, usize)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Ledger {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self::default()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One more reader of `interest`; the port is asked only for the first.
|
|
||||||
pub fn hold(&mut self, port: &mut dyn StatePort, interest: &Interest) -> SubscriptionId {
|
|
||||||
let (id, count) = self.held.entry(interest.clone()).or_insert_with(|| (port.subscribe(interest.clone()), 0));
|
|
||||||
*count += 1;
|
|
||||||
*id
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One reader fewer; the port is told when the last goes. Releasing what is not held does nothing.
|
|
||||||
pub fn release(&mut self, port: &mut dyn StatePort, interest: &Interest) {
|
|
||||||
let Some((id, count)) = self.held.get_mut(interest) else { return };
|
|
||||||
*count -= 1;
|
|
||||||
if *count == 0 {
|
|
||||||
let id = *id;
|
|
||||||
self.held.remove(interest);
|
|
||||||
port.unsubscribe(id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Move one reader from the interests it held to the ones it holds now: hold only the added,
|
|
||||||
/// release only the removed, touch nothing else.
|
|
||||||
pub fn diff(&mut self, port: &mut dyn StatePort, old: &HashSet<Interest>, new: &HashSet<Interest>) {
|
|
||||||
for added in new.difference(old) {
|
|
||||||
self.hold(port, added);
|
|
||||||
}
|
|
||||||
for removed in old.difference(new) {
|
|
||||||
self.release(port, removed);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// How many readers hold `interest`.
|
|
||||||
pub fn readers(&self, interest: &Interest) -> usize {
|
|
||||||
self.held.get(interest).map_or(0, |(_, count)| *count)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,146 +0,0 @@
|
||||||
//! What core may ask of state. The port reads and queues changes; nothing in it writes, and
|
|
||||||
//! it never awaits: core drains queued changes inside its frame.
|
|
||||||
|
|
||||||
pub mod ledger;
|
|
||||||
pub mod state;
|
|
||||||
|
|
||||||
pub use ledger::Ledger;
|
|
||||||
pub use state::StateValue;
|
|
||||||
|
|
||||||
use thing_contract::{AssetCatalog, CommandResult, CompositionDocument, ProviderId, RecordKey, SchemaId, SurfaceDocument};
|
|
||||||
|
|
||||||
/// One record: the provider that holds it, its schema and its key.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
|
||||||
pub struct Address {
|
|
||||||
pub provider: ProviderId,
|
|
||||||
pub schema: SchemaId,
|
|
||||||
pub key: RecordKey,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Every record of one provider and schema whose key starts with `key_prefix`.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
|
||||||
pub struct Prefix {
|
|
||||||
pub provider: ProviderId,
|
|
||||||
pub schema: SchemaId,
|
|
||||||
pub key_prefix: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
|
||||||
pub enum Interest {
|
|
||||||
Record(Address),
|
|
||||||
Prefix(Prefix),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Prefix {
|
|
||||||
pub fn matches(&self, address: &Address) -> bool {
|
|
||||||
self.provider == address.provider
|
|
||||||
&& self.schema == address.schema
|
|
||||||
&& address.key.as_str().starts_with(&self.key_prefix)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Interest {
|
|
||||||
/// Whether a change at `address` is of interest.
|
|
||||||
pub fn matches(&self, address: &Address) -> bool {
|
|
||||||
match self {
|
|
||||||
Interest::Record(record) => record == address,
|
|
||||||
Interest::Prefix(prefix) => prefix.matches(address),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
|
||||||
pub struct SubscriptionId(pub u64);
|
|
||||||
|
|
||||||
/// A record the port carries, decoded: a contract kind, or a provider's state by its schema's
|
|
||||||
/// member names. `State::schema` is the schema the record is stored under, which is not the
|
|
||||||
/// one asked for when the key holds a record of another.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub enum Record {
|
|
||||||
Surface(SurfaceDocument),
|
|
||||||
Composition(CompositionDocument),
|
|
||||||
Result(CommandResult),
|
|
||||||
Catalog(AssetCatalog),
|
|
||||||
State { schema: SchemaId, value: StateValue },
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct Entry {
|
|
||||||
pub address: Address,
|
|
||||||
pub record: Record,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A record the contract refused. `detail` is the decoder's message, which never carries a
|
|
||||||
/// value.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub struct Refusal {
|
|
||||||
pub address: Address,
|
|
||||||
pub kind: SchemaId,
|
|
||||||
pub detail: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The answer for one address. A refusal is never absence.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub enum Lookup {
|
|
||||||
Present(Entry),
|
|
||||||
Absent,
|
|
||||||
Refused(Refusal),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub enum Change {
|
|
||||||
Upsert(Entry),
|
|
||||||
Delete(Address),
|
|
||||||
Refused(Refusal),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Core's view of state. Object safe, and no method writes.
|
|
||||||
pub trait StatePort {
|
|
||||||
fn read(&self, address: &Address) -> Lookup;
|
|
||||||
|
|
||||||
/// One lookup per record under the prefix, in key order.
|
|
||||||
fn list(&self, prefix: &Prefix) -> Vec<Lookup>;
|
|
||||||
|
|
||||||
fn subscribe(&mut self, interest: Interest) -> SubscriptionId;
|
|
||||||
|
|
||||||
fn unsubscribe(&mut self, id: SubscriptionId);
|
|
||||||
|
|
||||||
/// Every change since the last drain that some interest matched when it happened, in mutation
|
|
||||||
/// order (unsubscribing does not recall changes already queued),
|
|
||||||
/// each once.
|
|
||||||
fn drain(&mut self) -> Vec<Change>;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn address(provider: &str, schema: &str, key: &str) -> Address {
|
|
||||||
Address { provider: ProviderId::new(provider), schema: SchemaId::new(schema), key: RecordKey::new(key) }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn prefix(provider: &str, schema: &str, key_prefix: &str) -> Prefix {
|
|
||||||
Prefix { provider: ProviderId::new(provider), schema: SchemaId::new(schema), key_prefix: key_prefix.into() }
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_prefix_matches_provider_schema_and_key_prefix_together() {
|
|
||||||
let under = prefix("p", "s", "row-");
|
|
||||||
assert!(under.matches(&address("p", "s", "row-1")));
|
|
||||||
assert!(under.matches(&address("p", "s", "row-")));
|
|
||||||
assert!(!under.matches(&address("q", "s", "row-1")));
|
|
||||||
assert!(!under.matches(&address("p", "t", "row-1")));
|
|
||||||
assert!(!under.matches(&address("p", "s", "col-1")));
|
|
||||||
assert!(!under.matches(&address("p", "s", "ro")));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn a_record_interest_matches_only_its_address() {
|
|
||||||
let interest = Interest::Record(address("p", "s", "k"));
|
|
||||||
assert!(interest.matches(&address("p", "s", "k")));
|
|
||||||
assert!(!interest.matches(&address("p", "s", "k2")));
|
|
||||||
assert!(!interest.matches(&address("q", "s", "k")));
|
|
||||||
assert!(Interest::Prefix(prefix("p", "s", "k")).matches(&address("p", "s", "k2")));
|
|
||||||
assert!(!Interest::Prefix(prefix("p", "s", "k")).matches(&address("p", "s", "j")));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,26 +0,0 @@
|
||||||
//! A provider record's value as core sees it. Core holds no bytes and no reader of them: a state
|
|
||||||
//! port implementation decodes a record with its schema's member names (the `thing-state` crate)
|
|
||||||
//! and hands core this tree.
|
|
||||||
|
|
||||||
/// A provider record's value: closed, ordered and named, with no case folding.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub enum StateValue {
|
|
||||||
Nil,
|
|
||||||
Bool(bool),
|
|
||||||
Int(i128),
|
|
||||||
Float(f64),
|
|
||||||
Text(String),
|
|
||||||
Bytes(Vec<u8>),
|
|
||||||
List(Vec<StateValue>),
|
|
||||||
Record(Vec<(String, StateValue)>),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl StateValue {
|
|
||||||
/// The member of a `Record` by exact name; `None` for any other shape or a missing name.
|
|
||||||
pub fn member(&self, name: &str) -> Option<&StateValue> {
|
|
||||||
match self {
|
|
||||||
StateValue::Record(members) => members.iter().find(|(member, _)| member == name).map(|(_, value)| value),
|
|
||||||
_ => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,37 +0,0 @@
|
||||||
//! The closed render-command list. Paint order is emission order: nothing carries a stacking value
|
|
||||||
//! or an escape hatch. Coordinates are f32 logical px (Pixels) or cells (Cells), already divided
|
|
||||||
//! by the scale; colours are literals, so a theme token cannot reach a backend by type.
|
|
||||||
|
|
||||||
use thing_contract::Rgba;
|
|
||||||
|
|
||||||
use crate::layout::{Rect, Run};
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub enum RenderCommand {
|
|
||||||
FillRect { rect: Rect, radius: f32, color: Rgba },
|
|
||||||
StrokeRect { rect: Rect, radius: f32, width: f32, color: Rgba },
|
|
||||||
/// One line of text at `origin` (its top-left).
|
|
||||||
Text { origin: (f32, f32), run: Run, color: Rgba },
|
|
||||||
Image { rect: Rect, uri: String, alt: String },
|
|
||||||
ClipPush { rect: Rect, radius: f32 },
|
|
||||||
ClipPop,
|
|
||||||
Polyline { points: Vec<(f32, f32)>, width: f32, color: Rgba },
|
|
||||||
Polygon { points: Vec<(f32, f32)>, color: Rgba },
|
|
||||||
Embed { rect: Rect, slot_kind: String, slot_id: String },
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Whether every ClipPush has its ClipPop, nested, and no ClipPop comes first.
|
|
||||||
pub fn balanced(commands: &[RenderCommand]) -> bool {
|
|
||||||
let mut open = 0usize;
|
|
||||||
for command in commands {
|
|
||||||
match command {
|
|
||||||
RenderCommand::ClipPush { .. } => open += 1,
|
|
||||||
RenderCommand::ClipPop => match open.checked_sub(1) {
|
|
||||||
Some(rest) => open = rest,
|
|
||||||
None => return false,
|
|
||||||
},
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
open == 0
|
|
||||||
}
|
|
||||||
|
|
@ -1,174 +0,0 @@
|
||||||
//! The leaves: control chrome, an Image's fit and the missing-asset placeholder. Core alone turns
|
|
||||||
//! fit and control state into geometry; no caret, selection or focus ring (those need edit and
|
|
||||||
//! focus state). Pixels and Cells share the lowering; only the inset and the stroke differ.
|
|
||||||
|
|
||||||
use 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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,307 +0,0 @@
|
||||||
//! Render: a `BoundTree`, its `LaidTree`, the scroll offsets and a theme become the closed command
|
|
||||||
//! list and the placed geometry hit-test, IME and accessibility read. A pure function: it reads
|
|
||||||
//! no port, no clock and no state, and equal inputs give an equal `Rendered`.
|
|
||||||
//!
|
|
||||||
//! This is the one place device px become logical px (divided by the scale) and scroll offsets
|
|
||||||
//! apply. Paint order is `LaidTree` order, which layout owns; render only looks nodes up.
|
|
||||||
|
|
||||||
mod command;
|
|
||||||
mod leaf;
|
|
||||||
mod plot;
|
|
||||||
mod scroll;
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
use thing_contract::{Anchor, BoxNode, ColorRef, Node, NodeId, Rgba};
|
|
||||||
|
|
||||||
pub use command::{RenderCommand, balanced};
|
|
||||||
pub use scroll::{ScrollOffsets, clamp};
|
|
||||||
|
|
||||||
use crate::bind::{Bound, BoundTree, Field};
|
|
||||||
use crate::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 });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,173 +0,0 @@
|
||||||
//! A Plot lowered to geometry: the domain, then Polylines, Polygons or FillRects. Pure and
|
|
||||||
//! bounded: a series of N points gives at most N vertices (Line), 2N (Area: each run of m >= 2
|
|
||||||
//! points adds two baseline vertices) or N rects (Bar); a non-finite or unrepresentable (f32) point is skipped with one diagnostic, never drawn.
|
|
||||||
|
|
||||||
use thing_contract::{PlotMark, PlotNode};
|
|
||||||
|
|
||||||
use super::Painter;
|
|
||||||
use super::command::RenderCommand;
|
|
||||||
use crate::bind::{Bound, Field};
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
use crate::layout::Rect;
|
|
||||||
|
|
||||||
/// One axis' domain: an explicit bound that is finite and not crossed by the other end is kept,
|
|
||||||
/// anything else takes the data value and is named; equal ends widen by 1 each way.
|
|
||||||
fn domain(explicit: (Option<f64>, Option<f64>), data: (f64, f64), names: (&'static str, &'static str), invalid: &mut Vec<&'static str>) -> (f64, f64) {
|
|
||||||
let (mut lo, mut hi) = (explicit.0.filter(|v| v.is_finite()), explicit.1.filter(|v| v.is_finite()));
|
|
||||||
if explicit.0.is_some() && lo.is_none() {
|
|
||||||
invalid.push(names.0);
|
|
||||||
}
|
|
||||||
if explicit.1.is_some() && hi.is_none() {
|
|
||||||
invalid.push(names.1);
|
|
||||||
}
|
|
||||||
if let (Some(a), Some(b)) = (lo, hi) {
|
|
||||||
if a > b {
|
|
||||||
invalid.extend([names.0, names.1]);
|
|
||||||
(lo, hi) = (None, None);
|
|
||||||
}
|
|
||||||
} else if let Some(a) = lo {
|
|
||||||
if a > data.1 {
|
|
||||||
invalid.push(names.0);
|
|
||||||
lo = None;
|
|
||||||
}
|
|
||||||
} else if let Some(b) = hi {
|
|
||||||
if b < data.0 {
|
|
||||||
invalid.push(names.1);
|
|
||||||
hi = None;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let (lo, hi) = (lo.unwrap_or(data.0), hi.unwrap_or(data.1));
|
|
||||||
if lo == hi { (lo - 1.0, hi + 1.0) } else { (lo, hi) }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where the series lands in `rect`: screen y grows down.
|
|
||||||
struct Frame {
|
|
||||||
rect: Rect,
|
|
||||||
x: (f64, f64),
|
|
||||||
y: (f64, f64),
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Frame {
|
|
||||||
/// A point of the series as f32 screen coordinates, `None` when either does not fit an f32.
|
|
||||||
fn at(&self, i: usize, v: f64) -> Option<(f32, f32)> {
|
|
||||||
let tx = halved(i as f64, self.x);
|
|
||||||
let x = (self.rect.x as f64 + tx * self.rect.w as f64) as f32;
|
|
||||||
let y = self.value(v) as f32;
|
|
||||||
(x.is_finite() && y.is_finite()).then_some((x, y))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Screen y of a value: y grows down. Halves keep a span near f64's range from overflowing.
|
|
||||||
fn value(&self, v: f64) -> f64 {
|
|
||||||
self.rect.y as f64 + self.rect.h as f64 - halved(v, self.y) * self.rect.h as f64
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where `v` falls in `(lo, hi)`, 0 to 1, computed on halves so `hi - lo` cannot overflow.
|
|
||||||
fn halved(v: f64, (lo, hi): (f64, f64)) -> f64 {
|
|
||||||
(v / 2.0 - lo / 2.0) / (hi / 2.0 - lo / 2.0)
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Painter<'_> {
|
|
||||||
pub(super) fn plot(&mut self, n: &thing_contract::PlotNode, rect: Rect) {
|
|
||||||
let tree = self.tree;
|
|
||||||
match tree.value(&n.common.id, Field::Series) {
|
|
||||||
Some(Bound::Series(values)) => self.plot_series(n, values, rect),
|
|
||||||
Some(Bound::Error(_)) => self.placeholder(&n.common.id, rect),
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A point that was not drawn is said once for the plot, whatever the reason.
|
|
||||||
fn dropped(&mut self, n: &PlotNode) {
|
|
||||||
self.out.diagnostics.push(Diagnostic {
|
|
||||||
code: Code::StyleValueInvalid,
|
|
||||||
surface: self.tree.resolved().document().record_key(),
|
|
||||||
node: Some(n.common.id.clone()),
|
|
||||||
detail: "series".to_string(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
fn plot_series(&mut self, n: &PlotNode, values: &[f64], rect: Rect) {
|
|
||||||
if values.is_empty() || !(rect.w > 0.0 && rect.h > 0.0) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let finite = || values.iter().copied().filter(|v| v.is_finite());
|
|
||||||
let low = finite().fold(f64::INFINITY, f64::min);
|
|
||||||
let high = finite().fold(f64::NEG_INFINITY, f64::max);
|
|
||||||
let data_y = if low <= high { (low, high) } else { (0.0, 0.0) };
|
|
||||||
let mut invalid = Vec::new();
|
|
||||||
let x = domain((n.x_min, n.x_max), (0.0, (values.len() - 1) as f64), ("x_min", "x_max"), &mut invalid);
|
|
||||||
let y = domain((n.y_min, n.y_max), data_y, ("y_min", "y_max"), &mut invalid);
|
|
||||||
for name in invalid {
|
|
||||||
self.out.diagnostics.push(Diagnostic {
|
|
||||||
code: Code::StyleValueInvalid,
|
|
||||||
surface: self.tree.resolved().document().record_key(),
|
|
||||||
node: Some(n.common.id.clone()),
|
|
||||||
detail: name.to_string(),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
let frame = Frame { rect, x, y };
|
|
||||||
let color = self.named(&n.common.id, "thing.plot.mark");
|
|
||||||
let width = match self.input.metrics {
|
|
||||||
crate::layout::Metrics::Cells => 1.0,
|
|
||||||
crate::layout::Metrics::Pixels => 2.0,
|
|
||||||
};
|
|
||||||
let base = frame.value(0.0f64.clamp(y.0, y.1));
|
|
||||||
if !(base as f32).is_finite() {
|
|
||||||
self.dropped(n);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let mut shapes = Vec::new();
|
|
||||||
let mut dropped = false;
|
|
||||||
match n.mark {
|
|
||||||
PlotMark::Bar => {
|
|
||||||
let slot = rect.w / values.len() as f32;
|
|
||||||
for (i, v) in values.iter().enumerate() {
|
|
||||||
let top = frame.value(*v);
|
|
||||||
let (y0, y1) = (top.min(base) as f32, top.max(base) as f32);
|
|
||||||
let bar = Rect { x: rect.x + slot * i as f32, y: y0, w: slot, h: y1 - y0 };
|
|
||||||
if v.is_finite() && [bar.x, bar.y, bar.w, bar.h].iter().all(|c| c.is_finite()) {
|
|
||||||
shapes.push(RenderCommand::FillRect { rect: bar, radius: 0.0, color: color.clone() });
|
|
||||||
} else {
|
|
||||||
dropped = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
PlotMark::Line | PlotMark::Area => {
|
|
||||||
let mut run: Vec<(f32, f32)> = Vec::new();
|
|
||||||
let flush = |run: &mut Vec<(f32, f32)>, shapes: &mut Vec<RenderCommand>| {
|
|
||||||
if run.len() >= 2 {
|
|
||||||
let mut points = std::mem::take(run);
|
|
||||||
if n.mark == PlotMark::Area {
|
|
||||||
let (first, last) = (points[0].0, points[points.len() - 1].0);
|
|
||||||
points.extend([(last, base as f32), (first, base as f32)]);
|
|
||||||
shapes.push(RenderCommand::Polygon { points, color: color.clone() });
|
|
||||||
} else {
|
|
||||||
shapes.push(RenderCommand::Polyline { points, width, color: color.clone() });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
run.clear();
|
|
||||||
};
|
|
||||||
for (i, v) in values.iter().enumerate() {
|
|
||||||
match v.is_finite().then(|| frame.at(i, *v)).flatten() {
|
|
||||||
Some(point) => run.push(point),
|
|
||||||
None => {
|
|
||||||
dropped = true;
|
|
||||||
flush(&mut run, &mut shapes);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
flush(&mut run, &mut shapes);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if dropped {
|
|
||||||
self.dropped(n);
|
|
||||||
}
|
|
||||||
if shapes.is_empty() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
self.out.commands.push(RenderCommand::ClipPush { rect, radius: 0.0 });
|
|
||||||
self.out.commands.extend(shapes);
|
|
||||||
self.out.commands.push(RenderCommand::ClipPop);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,38 +0,0 @@
|
||||||
//! Scroll positions: runtime state, never a layout input. Input writes them here and render reads
|
|
||||||
//! them here, both through the one `clamp`.
|
|
||||||
|
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
use thing_contract::NodeId;
|
|
||||||
|
|
||||||
use crate::layout::LaidNode;
|
|
||||||
|
|
||||||
/// `offset` held within `[0, max_scroll]` on each axis; a NaN offset is 0, and an axis that
|
|
||||||
/// cannot scroll holds 0.
|
|
||||||
pub fn clamp(offset: (f32, f32), max_scroll: (f32, f32)) -> (f32, f32) {
|
|
||||||
let axis = |v: f32, max: f32| if v.is_nan() || !(max > 0.0 && max.is_finite()) { 0.0 } else { v.clamp(0.0, max) };
|
|
||||||
(axis(offset.0, max_scroll.0), axis(offset.1, max_scroll.1))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where each scroll node is scrolled to, in device px (Pixels) or cells (Cells), as written.
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq)]
|
|
||||||
pub struct ScrollOffsets(HashMap<NodeId, (f32, f32)>);
|
|
||||||
|
|
||||||
impl ScrollOffsets {
|
|
||||||
pub fn set(&mut self, node: NodeId, offset: (f32, f32)) {
|
|
||||||
self.0.insert(node, offset);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get(&self, node: &NodeId) -> Option<(f32, f32)> {
|
|
||||||
self.0.get(node).copied()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The offset a laid node is drawn at: what was written, clamped to what layout says it can
|
|
||||||
/// scroll. A node that does not scroll, or has no offset, has none.
|
|
||||||
pub fn of(&self, node: &LaidNode) -> (f32, f32) {
|
|
||||||
match (self.0.get(&node.id), node.max_scroll) {
|
|
||||||
(Some(offset), Some(max)) => clamp(*offset, max),
|
|
||||||
_ => (0.0, 0.0),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,597 +0,0 @@
|
||||||
//! The substitution: depth first, order preserving. A surface and a composition body go through
|
|
||||||
//! the same functions; the scope says whether a Param is bound.
|
|
||||||
//!
|
|
||||||
//! Expanded ids: inside the expansion of Use `u`, the body root takes `u`'s id and every other
|
|
||||||
//! body id `b` becomes `u/b`. Arguments are expanded in the caller's scope before the body sees
|
|
||||||
//! them, so a Slot argument's nodes keep the ids they had in the caller.
|
|
||||||
|
|
||||||
use std::collections::{HashMap, HashSet};
|
|
||||||
|
|
||||||
use thing_contract::*;
|
|
||||||
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
use crate::port::{Address, Lookup, Record, StatePort};
|
|
||||||
|
|
||||||
use super::{Limits, std as thing_std, validate};
|
|
||||||
|
|
||||||
/// The deepest input the expander recurses into. This is a stack bound and not the depth rule: the
|
|
||||||
/// rule (`Limits::max_tree_depth`) is judged by validate on the finished tree, where a slot argument
|
|
||||||
/// the body never places does not count. It exists because an in-memory tree from a Rust caller can
|
|
||||||
/// be deeper than any decoded document (CultCache bounds decoded nesting at 256), and recursion
|
|
||||||
/// over it would overflow the stack. The recursion grows its own stack (`super::grow`), so the bound
|
|
||||||
/// holds on any thread.
|
|
||||||
const STACK_BOUND: usize = 1024;
|
|
||||||
|
|
||||||
/// A fault the nearest enclosing Use turns into a placeholder (`Invalid`), or one that ends the
|
|
||||||
/// whole expansion (`Limit`, or `Stack` for input too deep to recurse into).
|
|
||||||
pub(super) enum Fault {
|
|
||||||
Invalid(String),
|
|
||||||
Limit(String),
|
|
||||||
Stack(String),
|
|
||||||
}
|
|
||||||
|
|
||||||
type Res<T> = Result<T, Fault>;
|
|
||||||
|
|
||||||
fn invalid<T>(detail: String) -> Res<T> {
|
|
||||||
Err(Fault::Invalid(detail))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The expansion of one composition body: the Use's id and common, and the finished arguments.
|
|
||||||
struct Scope {
|
|
||||||
use_id: NodeId,
|
|
||||||
root_id: NodeId,
|
|
||||||
use_visible: BoolSource,
|
|
||||||
use_a11y: Option<TextSource>,
|
|
||||||
args: HashMap<String, ArgValue>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) struct Expander<'a> {
|
|
||||||
port: &'a dyn StatePort,
|
|
||||||
limits: &'a Limits,
|
|
||||||
surface: String,
|
|
||||||
provider: &'a ProviderId,
|
|
||||||
commands: HashSet<&'a CommandId>,
|
|
||||||
pub diagnostics: Vec<Diagnostic>,
|
|
||||||
pub reads: HashSet<Address>,
|
|
||||||
nodes: usize,
|
|
||||||
stack: Vec<CompositionRef>,
|
|
||||||
current: Option<NodeId>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn arm_name(value: &ArgValue) -> &'static str {
|
|
||||||
match value {
|
|
||||||
ArgValue::Text(_) => "Text",
|
|
||||||
ArgValue::Number(_) => "Number",
|
|
||||||
ArgValue::Bool(_) => "Bool",
|
|
||||||
ArgValue::Bind(_) => "Bind",
|
|
||||||
ArgValue::Collection(_) => "Collection",
|
|
||||||
ArgValue::Command(_) => "Command",
|
|
||||||
ArgValue::Slot(_) => "Slot",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn kind_name(kind: &ParamKind) -> &'static str {
|
|
||||||
match kind {
|
|
||||||
ParamKind::Text => "Text",
|
|
||||||
ParamKind::Number => "Number",
|
|
||||||
ParamKind::Bool => "Bool",
|
|
||||||
ParamKind::Bind => "Bind",
|
|
||||||
ParamKind::Collection => "Collection",
|
|
||||||
ParamKind::Command => "Command",
|
|
||||||
ParamKind::Slot => "Slot",
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn wrong_kind<T>(name: &ParamName, value: &ArgValue, position: &str) -> Res<T> {
|
|
||||||
invalid(format!("param '{}' is a {} argument, used as {position}", name.name, arm_name(value)))
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<'a> Expander<'a> {
|
|
||||||
pub fn new(document: &'a SurfaceDocument, port: &'a dyn StatePort, limits: &'a Limits) -> Self {
|
|
||||||
Self {
|
|
||||||
port,
|
|
||||||
limits,
|
|
||||||
surface: document.record_key(),
|
|
||||||
provider: &document.provider_id,
|
|
||||||
commands: document.commands.iter().map(|declared| &declared.id).collect(),
|
|
||||||
diagnostics: Vec::new(),
|
|
||||||
reads: HashSet::new(),
|
|
||||||
nodes: 0,
|
|
||||||
stack: Vec::new(),
|
|
||||||
current: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn diag(&mut self, code: Code, node: Option<NodeId>, detail: impl Into<String>) {
|
|
||||||
self.diagnostics.push(Diagnostic { code, surface: self.surface.clone(), node, detail: detail.into() });
|
|
||||||
}
|
|
||||||
|
|
||||||
fn unbound(&mut self, what: &str) {
|
|
||||||
let node = self.current.clone();
|
|
||||||
self.diag(Code::UnboundParam, node, format!("{what} outside a composition"));
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The surface root: no scope, no Use above it.
|
|
||||||
pub fn root(&mut self, root: &Node) -> Res<Node> {
|
|
||||||
self.node(root, None, 1, false)
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- positions ----------------------------------------------------------------------
|
|
||||||
|
|
||||||
fn id(&self, id: &NodeId, scope: Option<&Scope>) -> NodeId {
|
|
||||||
match scope {
|
|
||||||
None => id.clone(),
|
|
||||||
Some(scope) if *id == scope.root_id => scope.use_id.clone(),
|
|
||||||
Some(scope) => NodeId::new(format!("{}/{}", scope.use_id.as_str(), id.as_str())),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn fill(&self, provider: &Option<ProviderId>) -> Option<ProviderId> {
|
|
||||||
Some(provider.clone().unwrap_or_else(|| self.provider.clone()))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn bind(&self, bind: &Bind) -> Bind {
|
|
||||||
let source = match &bind.source {
|
|
||||||
StateSource::Record(state) => StateSource::Record(StateRef {
|
|
||||||
provider: self.fill(&state.provider),
|
|
||||||
schema: state.schema.clone(),
|
|
||||||
key: state.key.clone(),
|
|
||||||
}),
|
|
||||||
StateSource::Item => StateSource::Item,
|
|
||||||
};
|
|
||||||
Bind { source, member: bind.member.clone(), format: bind.format.clone() }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn arg_of<'s>(name: &ParamName, scope: &'s Scope) -> Res<&'s ArgValue> {
|
|
||||||
match scope.args.get(&name.name) {
|
|
||||||
Some(value) => Ok(value),
|
|
||||||
None => invalid(format!("the body names param '{}', which the composition does not declare", name.name)),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn text(&mut self, source: &TextSource, scope: Option<&Scope>) -> Res<TextSource> {
|
|
||||||
Ok(match (source, scope) {
|
|
||||||
(TextSource::Literal(_), _) => source.clone(),
|
|
||||||
(TextSource::Bound(bind), _) => TextSource::Bound(self.bind(bind)),
|
|
||||||
(TextSource::Param(name), None) => {
|
|
||||||
self.unbound(&format!("param '{}'", name.name));
|
|
||||||
source.clone()
|
|
||||||
}
|
|
||||||
(TextSource::Param(name), Some(scope)) => match Self::arg_of(name, scope)? {
|
|
||||||
ArgValue::Text(arg) => TextSource::Literal(TextLiteral { value: arg.value.clone() }),
|
|
||||||
ArgValue::Bind(bind) => TextSource::Bound(bind.clone()),
|
|
||||||
other => return wrong_kind(name, other, "text"),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn number(&mut self, source: &NumberSource, scope: Option<&Scope>) -> Res<NumberSource> {
|
|
||||||
Ok(match (source, scope) {
|
|
||||||
(NumberSource::Literal(_), _) => source.clone(),
|
|
||||||
(NumberSource::Bound(bind), _) => NumberSource::Bound(self.bind(bind)),
|
|
||||||
(NumberSource::Param(name), None) => {
|
|
||||||
self.unbound(&format!("param '{}'", name.name));
|
|
||||||
source.clone()
|
|
||||||
}
|
|
||||||
(NumberSource::Param(name), Some(scope)) => match Self::arg_of(name, scope)? {
|
|
||||||
ArgValue::Number(arg) => NumberSource::Literal(NumberLiteral { value: arg.value }),
|
|
||||||
ArgValue::Bind(bind) => NumberSource::Bound(bind.clone()),
|
|
||||||
other => return wrong_kind(name, other, "a number"),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn boolean(&mut self, source: &BoolSource, scope: Option<&Scope>) -> Res<BoolSource> {
|
|
||||||
Ok(match (source, scope) {
|
|
||||||
(BoolSource::Literal(_), _) => source.clone(),
|
|
||||||
(BoolSource::Bound(bind), _) => BoolSource::Bound(self.bind(bind)),
|
|
||||||
(BoolSource::Param(name), None) => {
|
|
||||||
self.unbound(&format!("param '{}'", name.name));
|
|
||||||
source.clone()
|
|
||||||
}
|
|
||||||
(BoolSource::Param(name), Some(scope)) => match Self::arg_of(name, scope)? {
|
|
||||||
ArgValue::Bool(arg) => BoolSource::Literal(BoolLiteral { value: arg.value }),
|
|
||||||
ArgValue::Bind(bind) => BoolSource::Bound(bind.clone()),
|
|
||||||
other => return wrong_kind(name, other, "a bool"),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Substitution only: the form an argument takes, before any position judges it.
|
|
||||||
fn subst_collection(&mut self, source: &CollectionSource, scope: Option<&Scope>) -> Res<CollectionSource> {
|
|
||||||
Ok(match (source, scope) {
|
|
||||||
(CollectionSource::Records(records), _) => CollectionSource::Records(RecordsSource {
|
|
||||||
provider: self.fill(&records.provider),
|
|
||||||
schema: records.schema.clone(),
|
|
||||||
key_prefix: records.key_prefix.clone(),
|
|
||||||
}),
|
|
||||||
(CollectionSource::Member(bind), _) => CollectionSource::Member(self.bind(bind)),
|
|
||||||
(CollectionSource::Param(_), None) => source.clone(),
|
|
||||||
(CollectionSource::Param(name), Some(scope)) => match Self::arg_of(name, scope)? {
|
|
||||||
ArgValue::Collection(arg) => arg.source.clone(),
|
|
||||||
other => return wrong_kind(name, other, "a collection"),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn collection(&mut self, source: &CollectionSource, scope: Option<&Scope>) -> Res<CollectionSource> {
|
|
||||||
let found = self.subst_collection(source, scope)?;
|
|
||||||
if let CollectionSource::Param(name) = &found {
|
|
||||||
self.unbound(&format!("param '{}'", name.name));
|
|
||||||
}
|
|
||||||
Ok(found)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn subst_command(&mut self, command: &CommandRef, scope: Option<&Scope>) -> Res<CommandRef> {
|
|
||||||
Ok(match (command, scope) {
|
|
||||||
(_, None) => command.clone(),
|
|
||||||
(CommandRef::Id(id), Some(_)) => {
|
|
||||||
return invalid(format!(
|
|
||||||
"the body names command '{}'; a composition takes its commands as params",
|
|
||||||
id.id.as_str()
|
|
||||||
));
|
|
||||||
}
|
|
||||||
(CommandRef::Param(name), Some(scope)) => match Self::arg_of(name, scope)? {
|
|
||||||
ArgValue::Command(arg) => arg.command.clone(),
|
|
||||||
other => return wrong_kind(name, other, "a command"),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A command at its final position: declared by the surface, and no Param.
|
|
||||||
fn command(&mut self, command: &CommandRef, scope: Option<&Scope>) -> Res<CommandRef> {
|
|
||||||
let found = self.subst_command(command, scope)?;
|
|
||||||
match &found {
|
|
||||||
CommandRef::Id(id) if !self.commands.contains(&id.id) => {
|
|
||||||
let node = self.current.clone();
|
|
||||||
self.diag(Code::UndeclaredCommand, node, format!("command '{}' is not declared", id.id.as_str()));
|
|
||||||
}
|
|
||||||
CommandRef::Param(name) => self.unbound(&format!("param '{}'", name.name)),
|
|
||||||
CommandRef::Id(_) => {}
|
|
||||||
}
|
|
||||||
Ok(found)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn common(&mut self, common: &NodeCommon, scope: Option<&Scope>, root: bool) -> Res<NodeCommon> {
|
|
||||||
let id = self.id(&common.id, scope);
|
|
||||||
self.current = Some(id.clone());
|
|
||||||
match scope {
|
|
||||||
// A body root is the Use: its id, and its visibility and label unless the body labels it.
|
|
||||||
Some(scope) if root => {
|
|
||||||
if common.visible != BoolSource::Literal(BoolLiteral { value: true }) {
|
|
||||||
return invalid("the body root's visible is not the literal true; visibility is the Use's".into());
|
|
||||||
}
|
|
||||||
let a11y_label = match (&scope.use_a11y, &common.a11y_label) {
|
|
||||||
(Some(label), _) => Some(label.clone()),
|
|
||||||
(None, Some(label)) => Some(self.text(label, Some(scope))?),
|
|
||||||
(None, None) => None,
|
|
||||||
};
|
|
||||||
Ok(NodeCommon { id, visible: scope.use_visible.clone(), a11y_label })
|
|
||||||
}
|
|
||||||
_ => {
|
|
||||||
let visible = self.boolean(&common.visible, scope)?;
|
|
||||||
let a11y_label = common.a11y_label.as_ref().map(|label| self.text(label, scope)).transpose()?;
|
|
||||||
Ok(NodeCommon { id, visible, a11y_label })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- nodes --------------------------------------------------------------------------
|
|
||||||
|
|
||||||
fn count(&mut self, added: usize) -> Res<()> {
|
|
||||||
self.nodes += added;
|
|
||||||
if self.nodes > self.limits.max_nodes {
|
|
||||||
return Err(Fault::Limit(format!("the expansion passed {} nodes", self.limits.max_nodes)));
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A child list. In a composition body a Slot is replaced by the nodes passed for it.
|
|
||||||
fn children(&mut self, list: &[Node], scope: Option<&Scope>, depth: usize) -> Res<Vec<Node>> {
|
|
||||||
let mut out = Vec::with_capacity(list.len());
|
|
||||||
for node in list {
|
|
||||||
match (node, scope) {
|
|
||||||
(Node::Slot(slot), Some(scope)) => match Self::arg_of(&slot.param, scope)? {
|
|
||||||
ArgValue::Slot(arg) => {
|
|
||||||
self.count(arg.nodes.iter().map(validate::size).sum())?;
|
|
||||||
out.extend(arg.nodes.iter().map(clone_deep));
|
|
||||||
}
|
|
||||||
other => return wrong_kind(&slot.param, other, "a slot"),
|
|
||||||
},
|
|
||||||
_ => out.push(self.node(node, scope, depth, false)?),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(out)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn node(&mut self, node: &Node, scope: Option<&Scope>, depth: usize, root: bool) -> Res<Node> {
|
|
||||||
super::grow(|| self.node_at(node, scope, depth, root))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn node_at(&mut self, node: &Node, scope: Option<&Scope>, depth: usize, root: bool) -> Res<Node> {
|
|
||||||
if depth > STACK_BOUND {
|
|
||||||
return Err(Fault::Stack(format!("the input nests deeper than {STACK_BOUND} levels")));
|
|
||||||
}
|
|
||||||
self.count(1)?;
|
|
||||||
// Each arm settles its own positions first and its child lists last: a diagnostic names the
|
|
||||||
// node being expanded, and a child list moves `current` on.
|
|
||||||
Ok(match node {
|
|
||||||
Node::Slot(slot) => match scope {
|
|
||||||
Some(_) => {
|
|
||||||
return invalid(format!(
|
|
||||||
"Slot '{}' is not in a child list of the body; a slot stands only in Box.children, \
|
|
||||||
Button.content or Overlay.children",
|
|
||||||
slot.param.name
|
|
||||||
));
|
|
||||||
}
|
|
||||||
None => {
|
|
||||||
self.current = None;
|
|
||||||
self.unbound(&format!("Slot '{}'", slot.param.name));
|
|
||||||
node.clone()
|
|
||||||
}
|
|
||||||
},
|
|
||||||
Node::Use(used) => self.expand_use(used, scope, depth, root)?,
|
|
||||||
Node::Box(b) => {
|
|
||||||
let common = self.common(&b.common, scope, root)?;
|
|
||||||
let children = self.children(&b.children, scope, depth + 1)?;
|
|
||||||
Node::Box(BoxNode { common, style: b.style.clone(), paint: b.paint.clone(), role: b.role.clone(), children })
|
|
||||||
}
|
|
||||||
Node::Text(t) => {
|
|
||||||
let common = self.common(&t.common, scope, root)?;
|
|
||||||
let content = self.text(&t.content, scope)?;
|
|
||||||
Node::Text(TextNode { common, content, ..t.clone() })
|
|
||||||
}
|
|
||||||
Node::Image(i) => {
|
|
||||||
let common = self.common(&i.common, scope, root)?;
|
|
||||||
let alt = self.text(&i.alt, scope)?;
|
|
||||||
Node::Image(ImageNode { common, alt, ..i.clone() })
|
|
||||||
}
|
|
||||||
Node::Button(b) => {
|
|
||||||
let common = self.common(&b.common, scope, root)?;
|
|
||||||
let on_activate = self.command(&b.on_activate, scope)?;
|
|
||||||
let enabled = self.boolean(&b.enabled, scope)?;
|
|
||||||
let content = self.children(&b.content, scope, depth + 1)?;
|
|
||||||
Node::Button(ButtonNode { common, content, on_activate, enabled })
|
|
||||||
}
|
|
||||||
Node::Toggle(t) => {
|
|
||||||
let common = self.common(&t.common, scope, root)?;
|
|
||||||
let checked = self.boolean(&t.checked, scope)?;
|
|
||||||
let on_change = self.command(&t.on_change, scope)?;
|
|
||||||
Node::Toggle(ToggleNode { common, checked, on_change })
|
|
||||||
}
|
|
||||||
Node::Slider(s) => {
|
|
||||||
let common = self.common(&s.common, scope, root)?;
|
|
||||||
let value = self.number(&s.value, scope)?;
|
|
||||||
let commit = self.command(&s.commit, scope)?;
|
|
||||||
Node::Slider(SliderNode { common, value, commit, ..s.clone() })
|
|
||||||
}
|
|
||||||
Node::TextInput(t) => {
|
|
||||||
let common = self.common(&t.common, scope, root)?;
|
|
||||||
let placeholder = self.text(&t.placeholder, scope)?;
|
|
||||||
let initial = self.text(&t.initial, scope)?;
|
|
||||||
let submit = self.command(&t.submit, scope)?;
|
|
||||||
Node::TextInput(TextInputNode { common, placeholder, initial, submit, ..t.clone() })
|
|
||||||
}
|
|
||||||
Node::Select(s) => {
|
|
||||||
let common = self.common(&s.common, scope, root)?;
|
|
||||||
let options = match &s.options {
|
|
||||||
OptionList::Literal(_) => s.options.clone(),
|
|
||||||
OptionList::Bound(bound) => OptionList::Bound(BoundOptions {
|
|
||||||
collection: self.collection(&bound.collection, scope)?,
|
|
||||||
value_member: bound.value_member.clone(),
|
|
||||||
label_member: bound.label_member.clone(),
|
|
||||||
}),
|
|
||||||
};
|
|
||||||
let value = self.bind(&s.value);
|
|
||||||
let on_change = self.command(&s.on_change, scope)?;
|
|
||||||
Node::Select(SelectNode { common, options, value, on_change })
|
|
||||||
}
|
|
||||||
Node::Repeat(r) => {
|
|
||||||
let common = self.common(&r.common, scope, root)?;
|
|
||||||
let collection = self.collection(&r.collection, scope)?;
|
|
||||||
let template = std::boxed::Box::new(self.node(&r.template, scope, depth + 1, false)?);
|
|
||||||
Node::Repeat(RepeatNode { common, collection, key_member: r.key_member.clone(), template })
|
|
||||||
}
|
|
||||||
Node::Overlay(o) => {
|
|
||||||
let common = self.common(&o.common, scope, root)?;
|
|
||||||
let anchor = match &o.anchor {
|
|
||||||
Anchor::Viewport => Anchor::Viewport,
|
|
||||||
Anchor::Node(anchor) => Anchor::Node(AnchorNode { node: self.id(&anchor.node, scope) }),
|
|
||||||
};
|
|
||||||
let dismiss = self.command(&o.dismiss, scope)?;
|
|
||||||
let children = self.children(&o.children, scope, depth + 1)?;
|
|
||||||
Node::Overlay(OverlayNode { common, anchor, modal: o.modal, dismiss, children })
|
|
||||||
}
|
|
||||||
Node::Plot(p) => {
|
|
||||||
let common = self.common(&p.common, scope, root)?;
|
|
||||||
Node::Plot(PlotNode { common, series: self.bind(&p.series), ..p.clone() })
|
|
||||||
}
|
|
||||||
Node::Embed(e) => {
|
|
||||||
let common = self.common(&e.common, scope, root)?;
|
|
||||||
Node::Embed(EmbedNode { common, ..e.clone() })
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- compositions -------------------------------------------------------------------
|
|
||||||
|
|
||||||
fn load(&mut self, reference: &CompositionRef) -> Result<CompositionDocument, (Code, String)> {
|
|
||||||
let name = format!("{}.{}.v{}", reference.publisher, reference.name.as_str(), reference.version.get());
|
|
||||||
if reference.publisher == thing_std::PUBLISHER {
|
|
||||||
return thing_std::lookup(reference.name.as_str(), reference.version)
|
|
||||||
.ok_or((Code::UnresolvedUse, format!("no compiled-in composition {name}")));
|
|
||||||
}
|
|
||||||
let address = Address {
|
|
||||||
provider: ProviderId::new(reference.publisher.clone()),
|
|
||||||
schema: SchemaId::new(CompositionDocument::SCHEMA_NAME),
|
|
||||||
key: RecordKey::new(reference.record_key()),
|
|
||||||
};
|
|
||||||
self.reads.insert(address.clone());
|
|
||||||
match self.port.read(&address) {
|
|
||||||
Lookup::Present(entry) => match entry.record {
|
|
||||||
Record::Composition(composition) => Ok(composition),
|
|
||||||
_ => Err((Code::CompositionInvalid, format!("the record at {name} is not a composition"))),
|
|
||||||
},
|
|
||||||
Lookup::Absent => Err((Code::UnresolvedUse, format!("no composition published at {name}"))),
|
|
||||||
Lookup::Refused(refusal) => Err((Code::DecodeRefused, format!("{name}: {}", refusal.detail))),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The first thing wrong with the composition against its Use, if anything.
|
|
||||||
fn misfit(reference: &CompositionRef, composition: &CompositionDocument, args: &[Arg]) -> Option<String> {
|
|
||||||
if composition.publisher != reference.publisher
|
|
||||||
|| composition.name != reference.name
|
|
||||||
|| composition.version != reference.version
|
|
||||||
{
|
|
||||||
return Some("the composition record's publisher, name or version differs from the Use's reference".into());
|
|
||||||
}
|
|
||||||
let mut declared: HashMap<&str, &ParamKind> = HashMap::new();
|
|
||||||
for param in &composition.params {
|
|
||||||
if declared.insert(¶m.name, ¶m.kind).is_some() {
|
|
||||||
return Some(format!("the composition declares param '{}' twice", param.name));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let mut given: HashSet<&str> = HashSet::new();
|
|
||||||
for arg in args {
|
|
||||||
if !given.insert(&arg.name) {
|
|
||||||
return Some(format!("argument '{}' is given twice", arg.name));
|
|
||||||
}
|
|
||||||
match declared.get(arg.name.as_str()) {
|
|
||||||
None => return Some(format!("argument '{}' names no param of the composition", arg.name)),
|
|
||||||
Some(kind) if kind_name(kind) != arm_name(&arg.value) => {
|
|
||||||
return Some(format!(
|
|
||||||
"argument '{}' is a {} but the param is a {}",
|
|
||||||
arg.name,
|
|
||||||
arm_name(&arg.value),
|
|
||||||
kind_name(kind)
|
|
||||||
));
|
|
||||||
}
|
|
||||||
Some(_) => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
composition
|
|
||||||
.params
|
|
||||||
.iter()
|
|
||||||
.find(|param| !given.contains(param.name.as_str()))
|
|
||||||
.map(|param| format!("param '{}' has no argument", param.name))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An argument in the caller's scope: the form the body will place.
|
|
||||||
fn arg(&mut self, value: &ArgValue, scope: Option<&Scope>, depth: usize) -> Res<ArgValue> {
|
|
||||||
Ok(match value {
|
|
||||||
ArgValue::Text(_) | ArgValue::Number(_) | ArgValue::Bool(_) => value.clone(),
|
|
||||||
ArgValue::Bind(bind) => ArgValue::Bind(self.bind(bind)),
|
|
||||||
ArgValue::Collection(arg) => {
|
|
||||||
ArgValue::Collection(CollectionArg { source: self.subst_collection(&arg.source, scope)? })
|
|
||||||
}
|
|
||||||
ArgValue::Command(arg) => ArgValue::Command(CommandArg { command: self.subst_command(&arg.command, scope)? }),
|
|
||||||
ArgValue::Slot(arg) => ArgValue::Slot(SlotArg { nodes: self.children(&arg.nodes, scope, depth + 1)? }),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn expand_use(&mut self, used: &UseNode, scope: Option<&Scope>, depth: usize, root: bool) -> Res<Node> {
|
|
||||||
let common = self.common(&used.common, scope, root)?;
|
|
||||||
let here = common.id.clone();
|
|
||||||
let reference = &used.composition;
|
|
||||||
let placeholder = |common: NodeCommon| Node::Use(UseNode { common, composition: reference.clone(), args: vec![] });
|
|
||||||
|
|
||||||
let repeats = self.stack.contains(reference);
|
|
||||||
if repeats || self.stack.len() >= self.limits.max_use_depth {
|
|
||||||
let why = if repeats { "uses itself" } else { "is nested too deep" };
|
|
||||||
self.diag(Code::CompositionCycle, Some(here), format!("the composition {why}"));
|
|
||||||
return Ok(placeholder(common));
|
|
||||||
}
|
|
||||||
let composition = match self.load(reference) {
|
|
||||||
Ok(composition) => composition,
|
|
||||||
Err((code, detail)) => {
|
|
||||||
self.diag(code, Some(here), detail);
|
|
||||||
return Ok(placeholder(common));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if let Some(detail) = Self::misfit(reference, &composition, &used.args) {
|
|
||||||
self.diag(Code::CompositionInvalid, Some(here), detail);
|
|
||||||
return Ok(placeholder(common));
|
|
||||||
}
|
|
||||||
|
|
||||||
let mark = self.diagnostics.len();
|
|
||||||
let mut args = HashMap::new();
|
|
||||||
for arg in &used.args {
|
|
||||||
args.insert(arg.name.clone(), self.arg(&arg.value, scope, depth)?);
|
|
||||||
}
|
|
||||||
let inner = Scope {
|
|
||||||
use_id: here.clone(),
|
|
||||||
root_id: body_id(&composition.body),
|
|
||||||
use_visible: common.visible.clone(),
|
|
||||||
use_a11y: common.a11y_label.clone(),
|
|
||||||
args,
|
|
||||||
};
|
|
||||||
self.stack.push(reference.clone());
|
|
||||||
let expanded = self.node(&composition.body, Some(&inner), depth, true);
|
|
||||||
self.stack.pop();
|
|
||||||
match expanded {
|
|
||||||
Ok(node) => Ok(node),
|
|
||||||
Err(Fault::Invalid(detail)) => {
|
|
||||||
self.diagnostics.truncate(mark);
|
|
||||||
self.diag(Code::CompositionInvalid, Some(here), detail);
|
|
||||||
Ok(placeholder(common))
|
|
||||||
}
|
|
||||||
Err(limit) => Err(limit),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The id of a body root. A Slot has none, and the body fails on it before an id is read.
|
|
||||||
/// A copy of an expanded subtree that grows its own stack. The derived `Clone` of `Node` costs about
|
|
||||||
/// 12 KiB of debug stack per level, so a spliced slot argument up to `STACK_BOUND` levels deep would
|
|
||||||
/// overflow it; each container here recurses through `grow`. An expanded subtree holds no Slot and no
|
|
||||||
/// Use with arguments, so the four containers are the only nodes that hold nodes.
|
|
||||||
fn clone_deep(node: &Node) -> Node {
|
|
||||||
super::grow(|| match node {
|
|
||||||
Node::Box(b) => Node::Box(BoxNode {
|
|
||||||
common: b.common.clone(),
|
|
||||||
style: b.style.clone(),
|
|
||||||
paint: b.paint.clone(),
|
|
||||||
role: b.role.clone(),
|
|
||||||
children: b.children.iter().map(clone_deep).collect(),
|
|
||||||
}),
|
|
||||||
Node::Button(b) => Node::Button(ButtonNode {
|
|
||||||
common: b.common.clone(),
|
|
||||||
content: b.content.iter().map(clone_deep).collect(),
|
|
||||||
on_activate: b.on_activate.clone(),
|
|
||||||
enabled: b.enabled.clone(),
|
|
||||||
}),
|
|
||||||
Node::Overlay(o) => Node::Overlay(OverlayNode {
|
|
||||||
common: o.common.clone(),
|
|
||||||
anchor: o.anchor.clone(),
|
|
||||||
modal: o.modal,
|
|
||||||
dismiss: o.dismiss.clone(),
|
|
||||||
children: o.children.iter().map(clone_deep).collect(),
|
|
||||||
}),
|
|
||||||
Node::Repeat(r) => Node::Repeat(RepeatNode {
|
|
||||||
common: r.common.clone(),
|
|
||||||
collection: r.collection.clone(),
|
|
||||||
key_member: r.key_member.clone(),
|
|
||||||
template: std::boxed::Box::new(clone_deep(&r.template)),
|
|
||||||
}),
|
|
||||||
other => other.clone(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn body_id(node: &Node) -> NodeId {
|
|
||||||
match node {
|
|
||||||
Node::Box(n) => n.common.id.clone(),
|
|
||||||
Node::Text(n) => n.common.id.clone(),
|
|
||||||
Node::Image(n) => n.common.id.clone(),
|
|
||||||
Node::Button(n) => n.common.id.clone(),
|
|
||||||
Node::Toggle(n) => n.common.id.clone(),
|
|
||||||
Node::Slider(n) => n.common.id.clone(),
|
|
||||||
Node::TextInput(n) => n.common.id.clone(),
|
|
||||||
Node::Select(n) => n.common.id.clone(),
|
|
||||||
Node::Repeat(n) => n.common.id.clone(),
|
|
||||||
Node::Overlay(n) => n.common.id.clone(),
|
|
||||||
Node::Plot(n) => n.common.id.clone(),
|
|
||||||
Node::Embed(n) => n.common.id.clone(),
|
|
||||||
Node::Use(n) => n.common.id.clone(),
|
|
||||||
Node::Slot(_) => NodeId::new(""),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,165 +0,0 @@
|
||||||
//! The Resolver: per surface, the highest version offered, the last good tree and the composition
|
|
||||||
//! interests that tree's resolution read. It is handed the changes the frame owner drained and
|
|
||||||
//! never drains itself. Every re-resolve reads the port again; no composition is cached here. The
|
|
||||||
//! interests are held through the shared `Ledger`, so the Binder and the Resolver count one
|
|
||||||
//! subscription per address.
|
|
||||||
|
|
||||||
use std::collections::{HashMap, HashSet};
|
|
||||||
|
|
||||||
use thing_contract::{DatabaseEntry, SurfaceDocument, Version};
|
|
||||||
|
|
||||||
use super::{Limits, ResolvedTree, resolve};
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
use crate::port::{Address, Change, Interest, Ledger, Record, StatePort};
|
|
||||||
|
|
||||||
/// What the Resolver holds of one surface.
|
|
||||||
struct Held {
|
|
||||||
/// The highest version offered, accepted or refused: the only one resolved again.
|
|
||||||
document: SurfaceDocument,
|
|
||||||
/// The last tree a resolve produced for a version above every earlier one.
|
|
||||||
tree: Option<ResolvedTree>,
|
|
||||||
/// The interests of the last resolve, which was of `document`.
|
|
||||||
interests: HashSet<Interest>,
|
|
||||||
/// Versions already reported stale.
|
|
||||||
reported: HashSet<Version>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What one `apply` did: its diagnostics, and each surface key whose displayed tree it replaced
|
|
||||||
/// (`true`) or dropped (`false`), sorted by key. A re-resolve that failed keeps its tree and is
|
|
||||||
/// not listed, so the frame owner never infers a change by comparing trees.
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq)]
|
|
||||||
pub struct Intake {
|
|
||||||
pub diagnostics: Vec<Diagnostic>,
|
|
||||||
pub changed: Vec<(String, bool)>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct Resolver {
|
|
||||||
limits: Limits,
|
|
||||||
surfaces: HashMap<String, Held>,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_surface(address: &Address) -> bool {
|
|
||||||
address.schema.as_str() == SurfaceDocument::SCHEMA_NAME
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Resolver {
|
|
||||||
pub fn new(limits: Limits) -> Self {
|
|
||||||
Self { limits, surfaces: HashMap::new() }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The tree displayed for a surface key: the last good one.
|
|
||||||
pub fn tree(&self, surface_key: &str) -> Option<&ResolvedTree> {
|
|
||||||
self.surfaces.get(surface_key).and_then(|held| held.tree.as_ref())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Drop a surface the consumer no longer shows: its interests are released and its entry goes
|
|
||||||
/// with no tombstone (the consumer leaving is not the provider deleting).
|
|
||||||
pub fn forget(&mut self, surface_key: &str, port: &mut dyn StatePort, ledger: &mut Ledger) {
|
|
||||||
if let Some(held) = self.surfaces.remove(surface_key) {
|
|
||||||
ledger.diff(port, &held.interests, &HashSet::new());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One drained change. A surface offer is judged by the version rule; a change at a
|
|
||||||
/// composition a held surface read resolves that surface again from its held document.
|
|
||||||
pub fn apply(&mut self, change: &Change, port: &mut dyn StatePort, ledger: &mut Ledger) -> Intake {
|
|
||||||
let address = match change {
|
|
||||||
Change::Upsert(entry) => &entry.address,
|
|
||||||
Change::Delete(address) => address,
|
|
||||||
Change::Refused(refusal) => &refusal.address,
|
|
||||||
};
|
|
||||||
if is_surface(address) {
|
|
||||||
return match change {
|
|
||||||
Change::Upsert(entry) => match &entry.record {
|
|
||||||
Record::Surface(document) => self.offer(document, port, ledger),
|
|
||||||
_ => Intake::default(),
|
|
||||||
},
|
|
||||||
Change::Delete(address) => {
|
|
||||||
// A tombstone: the highest version stays so an older one is not taken again,
|
|
||||||
// but the tree and the interests go.
|
|
||||||
let mut changed = Vec::new();
|
|
||||||
if let Some(held) = self.surfaces.get_mut(address.key.as_str()) {
|
|
||||||
if held.tree.take().is_some() {
|
|
||||||
changed.push((address.key.as_str().to_string(), false));
|
|
||||||
}
|
|
||||||
let released = std::mem::take(&mut held.interests);
|
|
||||||
ledger.diff(port, &released, &HashSet::new());
|
|
||||||
}
|
|
||||||
Intake { diagnostics: Vec::new(), changed }
|
|
||||||
}
|
|
||||||
Change::Refused(refusal) => Intake {
|
|
||||||
diagnostics: vec![Diagnostic {
|
|
||||||
code: Code::DecodeRefused,
|
|
||||||
surface: address.key.as_str().to_string(),
|
|
||||||
node: None,
|
|
||||||
detail: refusal.detail.clone(),
|
|
||||||
}],
|
|
||||||
changed: Vec::new(),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
let mut readers: Vec<String> = self
|
|
||||||
.surfaces
|
|
||||||
.iter()
|
|
||||||
.filter(|(_, held)| held.interests.iter().any(|interest| interest.matches(address)))
|
|
||||||
.map(|(key, _)| key.clone())
|
|
||||||
.collect();
|
|
||||||
readers.sort();
|
|
||||||
let mut intake = Intake::default();
|
|
||||||
for key in readers {
|
|
||||||
let document = self.surfaces[&key].document.clone();
|
|
||||||
let (diagnostics, replaced) = self.resolve_held(&key, document, port, ledger);
|
|
||||||
intake.diagnostics.extend(diagnostics);
|
|
||||||
if replaced {
|
|
||||||
intake.changed.push((key, true));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
intake
|
|
||||||
}
|
|
||||||
|
|
||||||
fn offer(&mut self, document: &SurfaceDocument, port: &mut dyn StatePort, ledger: &mut Ledger) -> Intake {
|
|
||||||
let key = document.record_key();
|
|
||||||
if let Some(held) = self.surfaces.get_mut(&key)
|
|
||||||
&& document.version <= held.document.version
|
|
||||||
{
|
|
||||||
// A subscribe replays the current record: the same document again is not news.
|
|
||||||
let diagnostics = if document.version == held.document.version && *document == held.document {
|
|
||||||
Vec::new()
|
|
||||||
} else if held.reported.insert(document.version) {
|
|
||||||
vec![Diagnostic {
|
|
||||||
code: Code::StaleVersionIgnored,
|
|
||||||
surface: key,
|
|
||||||
node: None,
|
|
||||||
detail: "version at or below the held version, which stays".into(),
|
|
||||||
}]
|
|
||||||
} else {
|
|
||||||
Vec::new()
|
|
||||||
};
|
|
||||||
return Intake { diagnostics, changed: Vec::new() };
|
|
||||||
}
|
|
||||||
let (diagnostics, replaced) = self.resolve_held(&key, document.clone(), port, ledger);
|
|
||||||
Intake { diagnostics, changed: if replaced { vec![(key, true)] } else { Vec::new() } }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Resolve `document` as the highest offered for `key`: a tree replaces the held one, no tree
|
|
||||||
/// keeps it. The interests become the reads either way. The flag is whether a tree replaced
|
|
||||||
/// the held one.
|
|
||||||
fn resolve_held(&mut self, key: &str, document: SurfaceDocument, port: &mut dyn StatePort, ledger: &mut Ledger) -> (Vec<Diagnostic>, bool) {
|
|
||||||
let resolution = resolve(&document, &*port, &self.limits);
|
|
||||||
let interests: HashSet<Interest> = resolution.reads.into_iter().map(Interest::Record).collect();
|
|
||||||
let held = self.surfaces.entry(key.to_string()).or_insert_with(|| Held {
|
|
||||||
document: document.clone(),
|
|
||||||
tree: None,
|
|
||||||
interests: HashSet::new(),
|
|
||||||
reported: HashSet::new(),
|
|
||||||
});
|
|
||||||
ledger.diff(port, &held.interests, &interests);
|
|
||||||
held.interests = interests;
|
|
||||||
held.document = document;
|
|
||||||
let replaced = resolution.tree.is_some();
|
|
||||||
if let Some(tree) = resolution.tree {
|
|
||||||
held.tree = Some(tree);
|
|
||||||
}
|
|
||||||
(resolution.diagnostics, replaced)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,111 +0,0 @@
|
||||||
//! Resolve: the pure expansion of a surface document into a tree with no composition left in it.
|
|
||||||
//! This is the only code that reads Thing Script structure (Use, Param, CommandRef, node ids).
|
|
||||||
//! It reads compositions through `StatePort::read` and `thing.std` from a compiled-in table,
|
|
||||||
//! holds no state, subscribes to nothing and never drains; `Resolver` is the stateful half.
|
|
||||||
|
|
||||||
mod expand;
|
|
||||||
mod intake;
|
|
||||||
pub mod std;
|
|
||||||
mod validate;
|
|
||||||
|
|
||||||
use thing_contract::SurfaceDocument;
|
|
||||||
|
|
||||||
pub use intake::{Intake, Resolver};
|
|
||||||
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
use crate::port::{Address, StatePort};
|
|
||||||
|
|
||||||
/// Stack left below which recursion moves to a fresh segment, and the segment's size: the values
|
|
||||||
/// cultcache-rs uses for decode. Every recursion over a tree runs through `grow`, so a tree as deep
|
|
||||||
/// as `STACK_BOUND` resolves on a default thread.
|
|
||||||
const RED_ZONE: usize = 512 * 1024;
|
|
||||||
const SEGMENT: usize = 2 * 1024 * 1024;
|
|
||||||
|
|
||||||
/// Runs one recursive step with room for the next, growing the stack when it is nearly spent.
|
|
||||||
pub(crate) fn grow<R>(step: impl FnOnce() -> R) -> R {
|
|
||||||
stacker::maybe_grow(RED_ZONE, SEGMENT, step)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The bounds of one expansion.
|
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
|
||||||
pub struct Limits {
|
|
||||||
/// Compositions nested in one another; a Use deeper than this is a placeholder.
|
|
||||||
pub max_use_depth: usize,
|
|
||||||
/// The contract's decode bound; a deeper expanded tree is refused.
|
|
||||||
pub max_tree_depth: usize,
|
|
||||||
/// Nodes in the expanded tree; more is refused.
|
|
||||||
pub max_nodes: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for Limits {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self { max_use_depth: 32, max_tree_depth: 256, max_nodes: 65_536 }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A surface document expanded: no Param of any kind remains, every command is declared, every
|
|
||||||
/// state reference names its provider, node ids are unique, and a Use remains only as a
|
|
||||||
/// placeholder leaf (its arguments emptied) beside a diagnostic. Only `resolve` builds one.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct ResolvedTree {
|
|
||||||
document: SurfaceDocument,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl ResolvedTree {
|
|
||||||
pub fn document(&self) -> &SurfaceDocument {
|
|
||||||
&self.document
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What one expansion found. `tree` is `None` when a fault refuses the whole document.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct Resolution {
|
|
||||||
pub tree: Option<ResolvedTree>,
|
|
||||||
/// Expansion faults in expansion pre-order, then the finished tree's faults (duplicate ids, depth)
|
|
||||||
/// in tree pre-order.
|
|
||||||
pub diagnostics: Vec<Diagnostic>,
|
|
||||||
/// Every non-std composition address consulted, whether present, absent or refused, once each, ordered
|
|
||||||
/// by provider, schema and key.
|
|
||||||
pub reads: Vec<Address>,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn resolve(document: &SurfaceDocument, port: &dyn StatePort, limits: &Limits) -> Resolution {
|
|
||||||
let mut expander = expand::Expander::new(document, port, limits);
|
|
||||||
let root = match expander.root(&document.root) {
|
|
||||||
Ok(root) => Some(root),
|
|
||||||
Err(expand::Fault::Limit(detail)) => {
|
|
||||||
expander.diag(Code::ExpansionLimit, None, detail);
|
|
||||||
None
|
|
||||||
}
|
|
||||||
Err(expand::Fault::Stack(detail)) => {
|
|
||||||
expander.diag(Code::TooDeepToResolve, None, detail);
|
|
||||||
None
|
|
||||||
}
|
|
||||||
Err(expand::Fault::Invalid(detail)) => {
|
|
||||||
expander.diag(Code::CompositionInvalid, None, detail);
|
|
||||||
None
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let mut diagnostics = ::std::mem::take(&mut expander.diagnostics);
|
|
||||||
let mut reads: Vec<Address> = ::std::mem::take(&mut expander.reads).into_iter().collect();
|
|
||||||
reads.sort_by(|a, b| {
|
|
||||||
let key = |address: &Address| (address.provider.as_str().to_string(), address.schema.as_str().to_string(), address.key.as_str().to_string());
|
|
||||||
key(a).cmp(&key(b))
|
|
||||||
});
|
|
||||||
let tree = root.and_then(|root| {
|
|
||||||
diagnostics.extend(validate::check(&root, limits, &document.record_key()));
|
|
||||||
let refused = diagnostics.iter().any(|diagnostic| diagnostic.code.refuses_document());
|
|
||||||
// Field by field: `..document.clone()` would clone the whole input tree to discard it.
|
|
||||||
(!refused).then(|| ResolvedTree {
|
|
||||||
document: SurfaceDocument {
|
|
||||||
provider_id: document.provider_id.clone(),
|
|
||||||
label: document.label.clone(),
|
|
||||||
version: document.version,
|
|
||||||
title: document.title.clone(),
|
|
||||||
root,
|
|
||||||
commands: document.commands.clone(),
|
|
||||||
},
|
|
||||||
})
|
|
||||||
});
|
|
||||||
Resolution { tree, diagnostics, reads }
|
|
||||||
}
|
|
||||||
|
|
@ -1,95 +0,0 @@
|
||||||
//! `thing.std`: the compositions compiled into core. The port is never asked for this
|
|
||||||
//! publisher, so no provider can shadow one.
|
|
||||||
|
|
||||||
use thing_contract::*;
|
|
||||||
|
|
||||||
/// The publisher whose compositions are compiled in.
|
|
||||||
pub const PUBLISHER: &str = "thing.std";
|
|
||||||
|
|
||||||
/// Every compiled-in composition.
|
|
||||||
pub fn all() -> Vec<CompositionDocument> {
|
|
||||||
vec![stat(), card()]
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(super) fn lookup(name: &str, version: Version) -> Option<CompositionDocument> {
|
|
||||||
all().into_iter().find(|composition| composition.name.as_str() == name && composition.version == version)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn segment(name: &str) -> Segment {
|
|
||||||
Segment::new(name).expect("a std name is a segment")
|
|
||||||
}
|
|
||||||
|
|
||||||
fn common(id: &str) -> NodeCommon {
|
|
||||||
NodeCommon { id: NodeId::new(id), visible: BoolSource::Literal(BoolLiteral { value: true }), a11y_label: None }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn text(id: &str, content: TextSource, style_token: &str) -> Node {
|
|
||||||
Node::Text(TextNode {
|
|
||||||
common: common(id),
|
|
||||||
content,
|
|
||||||
style_token: style_token.into(),
|
|
||||||
wrap: true,
|
|
||||||
max_lines: None,
|
|
||||||
selectable: false,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn param(name: &str) -> ParamName {
|
|
||||||
ParamName { name: name.into() }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn column(id: &str, children: Vec<Node>) -> Node {
|
|
||||||
let zero = || Dimension::Px(Scalar { value: 0.0 });
|
|
||||||
let auto = || Dimension::Auto;
|
|
||||||
let size = |width, height| Size2 { width, height };
|
|
||||||
let edges = |all: Dimension| Edges { top: all.clone(), right: all.clone(), bottom: all.clone(), left: all };
|
|
||||||
let style = BoxStyle {
|
|
||||||
display: Display::Flex,
|
|
||||||
direction: Direction::Column,
|
|
||||||
wrap: Wrap::NoWrap,
|
|
||||||
gap: size(zero(), Dimension::Px(Scalar { value: 4.0 })),
|
|
||||||
padding: edges(zero()),
|
|
||||||
margin: edges(zero()),
|
|
||||||
size: size(auto(), Dimension::Content),
|
|
||||||
min_size: size(zero(), zero()),
|
|
||||||
max_size: size(auto(), auto()),
|
|
||||||
position: Position::Relative,
|
|
||||||
inset: edges(auto()),
|
|
||||||
overflow: Overflow::Visible,
|
|
||||||
align_items: ItemAlign::Stretch,
|
|
||||||
align_self: ItemAlign::Auto,
|
|
||||||
align_content: ContentAlign::Start,
|
|
||||||
justify_content: ContentAlign::Start,
|
|
||||||
grow: 0.0,
|
|
||||||
shrink: 1.0,
|
|
||||||
basis: Dimension::Auto,
|
|
||||||
grid_columns: vec![],
|
|
||||||
grid_rows: vec![],
|
|
||||||
};
|
|
||||||
let paint = Paint { background: None, border: None, radius: 0.0 };
|
|
||||||
Node::Box(BoxNode { common: common(id), style, paint, role: Role::Group, children })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn composition(name: &str, params: &[(&str, ParamKind)], body: Node) -> CompositionDocument {
|
|
||||||
CompositionDocument {
|
|
||||||
publisher: PUBLISHER.into(),
|
|
||||||
name: segment(name),
|
|
||||||
version: Version::new(1).expect("version 1"),
|
|
||||||
params: params.iter().map(|(name, kind)| ParamDecl { name: (*name).into(), kind: kind.clone() }).collect(),
|
|
||||||
body,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A label over a bound value.
|
|
||||||
fn stat() -> CompositionDocument {
|
|
||||||
let label = text("stat-label", TextSource::Param(param("label")), "caption");
|
|
||||||
let value = text("stat-value", TextSource::Param(param("value")), "title");
|
|
||||||
composition("stat", &[("label", ParamKind::Text), ("value", ParamKind::Bind)], column("stat-root", vec![label, value]))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A title over the nodes passed for `body`.
|
|
||||||
fn card() -> CompositionDocument {
|
|
||||||
let title = text("card-title", TextSource::Param(param("title")), "title");
|
|
||||||
let slot = Node::Slot(SlotNode { param: param("body") });
|
|
||||||
composition("card", &[("title", ParamKind::Text), ("body", ParamKind::Slot)], column("card-root", vec![title, slot]))
|
|
||||||
}
|
|
||||||
|
|
@ -1,110 +0,0 @@
|
||||||
//! The one pass over the finished tree: ids unique, and the tree within its depth limit (a slot's
|
|
||||||
//! nodes are placed deeper than expand saw them). Commands, Params and Slots are judged where they
|
|
||||||
//! land and the node count is expand's alone (it must stop before it builds a tree it would refuse).
|
|
||||||
|
|
||||||
use std::collections::HashSet;
|
|
||||||
|
|
||||||
use thing_contract::{Node, NodeId};
|
|
||||||
|
|
||||||
use super::Limits;
|
|
||||||
use crate::diagnostic::{Code, Diagnostic};
|
|
||||||
|
|
||||||
/// The child nodes of a node, in order.
|
|
||||||
fn children(node: &Node) -> &[Node] {
|
|
||||||
match node {
|
|
||||||
Node::Box(b) => &b.children,
|
|
||||||
Node::Button(b) => &b.content,
|
|
||||||
Node::Overlay(o) => &o.children,
|
|
||||||
Node::Repeat(r) => std::slice::from_ref(&*r.template),
|
|
||||||
_ => &[],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn id(node: &Node) -> Option<&NodeId> {
|
|
||||||
match node {
|
|
||||||
Node::Box(n) => Some(&n.common.id),
|
|
||||||
Node::Text(n) => Some(&n.common.id),
|
|
||||||
Node::Image(n) => Some(&n.common.id),
|
|
||||||
Node::Button(n) => Some(&n.common.id),
|
|
||||||
Node::Toggle(n) => Some(&n.common.id),
|
|
||||||
Node::Slider(n) => Some(&n.common.id),
|
|
||||||
Node::TextInput(n) => Some(&n.common.id),
|
|
||||||
Node::Select(n) => Some(&n.common.id),
|
|
||||||
Node::Repeat(n) => Some(&n.common.id),
|
|
||||||
Node::Overlay(n) => Some(&n.common.id),
|
|
||||||
Node::Plot(n) => Some(&n.common.id),
|
|
||||||
Node::Embed(n) => Some(&n.common.id),
|
|
||||||
Node::Use(n) => Some(&n.common.id),
|
|
||||||
Node::Slot(_) => None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Nodes in the subtree, the node itself included.
|
|
||||||
pub(super) fn size(node: &Node) -> usize {
|
|
||||||
super::grow(|| 1 + children(node).iter().map(size).sum::<usize>())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Faults of the finished tree, in pre-order: duplicate ids, then depth. A tree deeper than the limit is not walked further.
|
|
||||||
pub(super) fn check(root: &Node, limits: &Limits, surface: &str) -> Vec<Diagnostic> {
|
|
||||||
let mut found = Vec::new();
|
|
||||||
let fault = |code, node: Option<&NodeId>, detail: String| Diagnostic {
|
|
||||||
code,
|
|
||||||
surface: surface.to_string(),
|
|
||||||
node: node.cloned(),
|
|
||||||
detail,
|
|
||||||
};
|
|
||||||
let mut seen: HashSet<&NodeId> = HashSet::new();
|
|
||||||
let mut too_deep = false;
|
|
||||||
let mut stack = vec![(root, 1usize)];
|
|
||||||
while let Some((node, depth)) = stack.pop() {
|
|
||||||
if depth > limits.max_tree_depth {
|
|
||||||
too_deep = true;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if let Some(id) = id(node) {
|
|
||||||
if !seen.insert(id) {
|
|
||||||
found.push(fault(Code::DuplicateNodeId, Some(id), format!("node id '{}' occurs twice", id.as_str())));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
stack.extend(children(node).iter().rev().map(|child| (child, depth + 1)));
|
|
||||||
}
|
|
||||||
if too_deep {
|
|
||||||
found.push(fault(Code::ExpansionLimit, None, format!("the tree is deeper than {} levels", limits.max_tree_depth)));
|
|
||||||
}
|
|
||||||
found
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use thing_testkit::build::{boxed, text};
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
/// Runs `work` with about `left` bytes of stack remaining: the stack is burned first, so a recursion
|
|
||||||
/// that does not grow its own runs out inside it.
|
|
||||||
#[inline(never)]
|
|
||||||
fn with_stack_left(left: usize, work: &mut dyn FnMut()) {
|
|
||||||
if stacker::remaining_stack().expect("the thread's stack limit is known") > left {
|
|
||||||
let burn = [0u8; 4096];
|
|
||||||
std::hint::black_box(&burn);
|
|
||||||
with_stack_left(left, work);
|
|
||||||
std::hint::black_box(&burn);
|
|
||||||
} else {
|
|
||||||
work();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn size_of_a_deep_subtree_grows_its_own_stack() {
|
|
||||||
// expand counts a slot argument with `size` after the argument was expanded, from wherever the
|
|
||||||
// stack stands; a 1,000-level argument must not run it out.
|
|
||||||
let mut deep = text("bottom", "x");
|
|
||||||
for level in 1..1000 {
|
|
||||||
deep = boxed(&format!("level-{level}"), vec![deep]);
|
|
||||||
}
|
|
||||||
let mut counted = 0;
|
|
||||||
with_stack_left(100 * 1024, &mut || counted = size(&deep));
|
|
||||||
assert_eq!(counted, 1000);
|
|
||||||
// Dropping a tree this deep needs the room the test thread has outside `with_stack_left`.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,317 +0,0 @@
|
||||||
//! The Cells text engine: `CellText` is the one constructor of terminal text and `CellMeasure` the
|
|
||||||
//! one `Measure` for Cells. Every width and every break a cell backend advances by is decided
|
|
||||||
//! here, per extended grapheme cluster, and no backend computes either.
|
|
||||||
//!
|
|
||||||
//! Order is sanitize, then segment and measure: the text is cleaned (controls become U+FFFD,
|
|
||||||
//! clusters without width are dropped) until segmenting it again changes nothing, so every width
|
|
||||||
//! recorded is the width of exactly the text a terminal receives.
|
|
||||||
//!
|
|
||||||
//! Breaking is CSS `white-space: pre-wrap` with `overflow-wrap: break-word`: mandatory breaks
|
|
||||||
//! always break, soft breaks are UAX #14 Allowed positions on a cluster boundary, trailing spaces
|
|
||||||
//! at a soft break hang (are not emitted), and an unbreakable segment wider than the line breaks
|
|
||||||
//! between clusters. A line takes at least one cluster, so at width 0 every cluster sits on its
|
|
||||||
//! own line. Text is laid out in logical order; bidi reordering is Pixels-only.
|
|
||||||
|
|
||||||
use unicode_linebreak::{BreakOpportunity, linebreaks};
|
|
||||||
use unicode_segmentation::UnicodeSegmentation;
|
|
||||||
use unicode_width::UnicodeWidthStr;
|
|
||||||
|
|
||||||
use crate::bind::Bound;
|
|
||||||
use crate::layout::{Avail, 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(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
//! Terminal text: what a string is made of in a cell grid. The one owner of every Cells width and
|
|
||||||
//! line break (Pixels text is the shaper's, behind the same `Measure` seam).
|
|
||||||
|
|
||||||
mod cells;
|
|
||||||
|
|
||||||
pub use cells::{CellMeasure, CellText};
|
|
||||||
|
|
@ -1,86 +0,0 @@
|
||||||
//! The theme a frame is drawn with: named colours and named text styles, resolved to literals
|
|
||||||
//! in render so a token never reaches a backend. Where a host's theme comes from is
|
|
||||||
//! `thing2:follow_up:theme-record-contract`; render takes a `&Theme`.
|
|
||||||
|
|
||||||
use std::collections::BTreeMap;
|
|
||||||
|
|
||||||
use thing_contract::{ColorRef, Rgba};
|
|
||||||
|
|
||||||
use crate::layout::CellStyle;
|
|
||||||
|
|
||||||
/// What a text style token draws as: the colour render emits, and the size and cell attributes
|
|
||||||
/// the text engine reads when it shapes the line.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct TextStyle {
|
|
||||||
pub color: Rgba,
|
|
||||||
pub size: f32,
|
|
||||||
pub cells: CellStyle,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct Theme {
|
|
||||||
pub colors: BTreeMap<String, Rgba>,
|
|
||||||
pub text: BTreeMap<String, TextStyle>,
|
|
||||||
/// Scrollbar thickness, logical px (one cell in Cells).
|
|
||||||
pub scrollbar: f32,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The colour a token the theme does not hold draws as, so the fault is visible.
|
|
||||||
pub fn fallback() -> Rgba {
|
|
||||||
Rgba { r: 0xff, g: 0x00, b: 0xff, a: 0xff }
|
|
||||||
}
|
|
||||||
|
|
||||||
fn rgba(hex: u32) -> Rgba {
|
|
||||||
Rgba { r: (hex >> 24) as u8, g: (hex >> 16) as u8, b: (hex >> 8) as u8, a: hex as u8 }
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Theme {
|
|
||||||
/// `thing.std`'s default: every token render and the fixtures use.
|
|
||||||
pub fn std() -> Self {
|
|
||||||
let colors = [
|
|
||||||
("thing.surface", 0x1e1e2eff),
|
|
||||||
("thing.error", 0xe5484dff),
|
|
||||||
("thing.placeholder", 0x6e6e80ff),
|
|
||||||
("thing.scrim", 0x00000099),
|
|
||||||
("thing.scrollbar.thumb", 0xffffff66),
|
|
||||||
("thing.control.fill", 0x2c2c3eff),
|
|
||||||
("thing.control.border", 0x4a4a60ff),
|
|
||||||
("thing.control.accent", 0x7c9cffff),
|
|
||||||
("thing.control.text", 0xeeeef4ff),
|
|
||||||
("thing.control.disabled", 0x3a3a48ff),
|
|
||||||
("thing.plot.mark", 0x7c9cffff),
|
|
||||||
]
|
|
||||||
.into_iter()
|
|
||||||
.map(|(name, hex)| (name.to_string(), rgba(hex)))
|
|
||||||
.collect();
|
|
||||||
let style = |hex: u32, size: f32, bold: bool| TextStyle {
|
|
||||||
color: rgba(hex),
|
|
||||||
size,
|
|
||||||
cells: CellStyle { bold, ..CellStyle::default() },
|
|
||||||
};
|
|
||||||
let text = [
|
|
||||||
("title", style(0xffffffff, 24.0, true)),
|
|
||||||
("body", style(0xeeeef4ff, 16.0, false)),
|
|
||||||
("thing.text", style(0xeeeef4ff, 16.0, false)),
|
|
||||||
("thing.text.placeholder", style(0x6e6e80ff, 16.0, false)),
|
|
||||||
]
|
|
||||||
.into_iter()
|
|
||||||
.map(|(name, style)| (name.to_string(), style))
|
|
||||||
.collect();
|
|
||||||
Self { colors, text, scrollbar: 6.0 }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The literal a colour is: a token the theme holds, or the literal itself. `None` is an
|
|
||||||
/// unknown token.
|
|
||||||
pub fn resolve(&self, color: &ColorRef) -> Option<Rgba> {
|
|
||||||
match color {
|
|
||||||
ColorRef::Rgba(literal) => Some(literal.clone()),
|
|
||||||
ColorRef::Token(token) => self.colors.get(&token.name).cloned(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A named colour of the theme's own (render's scrim, error and thumb).
|
|
||||||
pub fn color(&self, name: &str) -> Option<Rgba> {
|
|
||||||
self.colors.get(name).cloned()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,5 +0,0 @@
|
||||||
//! Wall time as core is told it: the host reads its clock and hands core the reading.
|
|
||||||
|
|
||||||
/// Unix milliseconds, UTC.
|
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
|
||||||
pub struct Timestamp(pub i64);
|
|
||||||
File diff suppressed because it is too large
Load diff
|
|
@ -1,260 +0,0 @@
|
||||||
//! The Cells text engine: pinned widths, sanitizing, wrapping, and that `measure` and `text`
|
|
||||||
//! agree. Vectors were checked against unicode-width 0.2.3 (ambiguous width narrow).
|
|
||||||
|
|
||||||
use thing_contract::{AssetEntry, NodeId};
|
|
||||||
use thing_core::bind::Bound;
|
|
||||||
use thing_core::layout::{Avail, Constraint, Leaf, Measure, Run, TextRequest};
|
|
||||||
use thing_core::text::{CellMeasure, CellText};
|
|
||||||
use thing_testkit::build::count;
|
|
||||||
|
|
||||||
fn widths(s: &str) -> Vec<u8> {
|
|
||||||
CellText::new(s).clusters().map(|(_, w)| w).collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn width_vectors() {
|
|
||||||
let vectors: &[(&str, &[u8])] = &[
|
|
||||||
("a", &[1]),
|
|
||||||
("\u{4e2d}", &[2]),
|
|
||||||
("\u{ff21}", &[2]),
|
|
||||||
("\u{d55c}", &[2]),
|
|
||||||
("e\u{301}", &[1]),
|
|
||||||
("\u{b1}", &[1]),
|
|
||||||
("\u{3b1}", &[1]),
|
|
||||||
("\u{1f600}", &[2]),
|
|
||||||
("\u{2764}", &[1]),
|
|
||||||
("\u{2764}\u{fe0f}", &[2]),
|
|
||||||
("\u{263a}\u{fe0e}", &[1]),
|
|
||||||
("\u{1f44d}\u{1f3fd}", &[2]),
|
|
||||||
("\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}", &[2]),
|
|
||||||
("\u{1f1ef}\u{1f1f5}", &[2]),
|
|
||||||
("\u{1f1ef}", &[1]),
|
|
||||||
("1\u{fe0f}\u{20e3}", &[2]),
|
|
||||||
("\u{1f3f3}\u{fe0f}\u{200d}\u{1f308}", &[2]),
|
|
||||||
("\u{1100}\u{1161}\u{11a8}", &[2]),
|
|
||||||
("\u{915}\u{94d}\u{937}", &[2]),
|
|
||||||
("\u{e01}\u{e33}", &[2]),
|
|
||||||
("\u{17d8}", &[3]),
|
|
||||||
("\u{a0}", &[1]),
|
|
||||||
("\u{644}\u{627}", &[1, 1]),
|
|
||||||
];
|
|
||||||
for (text, expected) in vectors {
|
|
||||||
assert_eq!(&widths(text), expected, "{text:?}");
|
|
||||||
assert_eq!(CellText::new(text).width(), expected.iter().map(|&w| u32::from(w)).sum::<u32>(), "{text:?} line width is the cluster sum");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn sanitizing() {
|
|
||||||
for c in ['\u{1b}', '\u{7f}', '\u{9b}'] {
|
|
||||||
let s = c.to_string();
|
|
||||||
assert_eq!((CellText::new(&s).as_str(), widths(&s)), ("\u{fffd}", vec![1]), "{c:?}");
|
|
||||||
}
|
|
||||||
assert_eq!(CellText::new("a\tb").as_str(), "a b");
|
|
||||||
assert_eq!(CellText::new("abcdefgh\ti").as_str(), "abcdefgh i");
|
|
||||||
for vanishing in ["\u{202e}", "\u{200b}", "\u{ad}", "\u{200d}", "\u{301}"] {
|
|
||||||
assert_eq!(CellText::new(vanishing).as_str(), "", "{vanishing:?}");
|
|
||||||
}
|
|
||||||
assert_eq!(CellText::new("\u{301}a").as_str(), "a");
|
|
||||||
assert_eq!(CellText::new("x\u{200b}y").as_str(), "xy");
|
|
||||||
// The break opportunity of a dropped cluster survives.
|
|
||||||
assert_eq!(lines("x\u{200b}y", 1), ["x", "y"]);
|
|
||||||
// A terminator handed straight to `new` is a control like any other.
|
|
||||||
assert_eq!(CellText::new("a\nb").as_str(), "a\u{fffd}b");
|
|
||||||
assert_eq!(CellText::new("a\u{2028}b").as_str(), "a\u{fffd}b");
|
|
||||||
assert_eq!(widths("a\u{2028}b"), [1, 1, 1]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn dropping_a_cluster_is_measured_after_the_drop() {
|
|
||||||
// woman, a dropped bidi control, skin tone: the terminal sees one 2-wide cluster.
|
|
||||||
let t = CellText::new("\u{1f469}\u{202c}\u{1f3fd}");
|
|
||||||
assert_eq!(t.as_str(), "\u{1f469}\u{1f3fd}");
|
|
||||||
assert_eq!(t.clusters().map(|(_, w)| w).collect::<Vec<_>>(), [2]);
|
|
||||||
// A control turned U+FFFD leaves the mark after it orphaned, and an orphan is dropped.
|
|
||||||
assert_eq!(CellText::new("\u{1b}\u{301}").as_str(), "\u{fffd}");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn tabs_stop_at_eight_from_the_start_of_the_line() {
|
|
||||||
assert_eq!(CellText::new("\t").as_str(), " ".repeat(8));
|
|
||||||
assert_eq!(CellText::new("\t\t").as_str(), " ".repeat(16));
|
|
||||||
assert_eq!(CellText::new("abcdefgh\t").as_str(), format!("abcdefgh{}", " ".repeat(8)));
|
|
||||||
assert_eq!(CellText::new("abc\t\td").as_str(), format!("abc{}d", " ".repeat(13)));
|
|
||||||
assert_eq!(CellText::new("\u{4e2d}\tx").as_str(), format!("\u{4e2d}{}x", " ".repeat(6)));
|
|
||||||
// After a soft break the stop counts from the wrapped line, not the paragraph.
|
|
||||||
assert_eq!(lines("aaaaaaaa bb\tc", 9), ["aaaaaaaa", "bb c"]);
|
|
||||||
// A tab is a space: it hangs at a soft break.
|
|
||||||
assert_eq!(lines("abcdef\tgh", 7), ["abcdef", "gh"]);
|
|
||||||
assert_eq!(lines("ab cd", 9), ["ab", "cd"]);
|
|
||||||
assert_eq!(lines("ab cd", 10), ["ab cd"]);
|
|
||||||
assert_eq!(leaf_measure("a b", true, None, Avail::MinContent).0, 1.0);
|
|
||||||
assert_eq!(leaf_measure("a b", false, None, Avail::MaxContent).0, 9.0);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn width_zero_is_one_cluster_per_line() {
|
|
||||||
assert_eq!(lines("abc", 0), ["a", "b", "c"]);
|
|
||||||
assert_eq!(lines("a b", 0), ["a", "b"]);
|
|
||||||
assert_eq!(lines("\u{4e2d}x", 0), ["\u{4e2d}", "x"]);
|
|
||||||
assert_eq!(lines(" a", 2), [" ", "a"]);
|
|
||||||
assert_eq!(layout_lines("abc", true, None, -3.0), ["a", "b", "c"]);
|
|
||||||
assert_eq!(layout_lines("abc", true, None, f32::NAN), ["a", "b", "c"]);
|
|
||||||
assert_eq!(leaf_measure("abc", true, None, Avail::Definite(0.0)), (1.0, 3.0));
|
|
||||||
assert!(lines("abc def", 0).iter().all(|l| !l.is_empty()));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn every_scalar_is_clean() {
|
|
||||||
for c in (0..=char::MAX as u32).filter_map(char::from_u32) {
|
|
||||||
let t = CellText::new(&c.to_string());
|
|
||||||
assert!(!t.as_str().chars().any(|c| c.is_control()), "{:#x}", c as u32);
|
|
||||||
assert!(t.clusters().all(|(_, w)| (1..=3).contains(&w)), "{:#x}", c as u32);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn leaf_measure(text: &str, wrap: bool, max_lines: Option<u32>, room: Avail) -> (f32, f32) {
|
|
||||||
let node = NodeId::new("n");
|
|
||||||
let content = Bound::Text(text.to_string());
|
|
||||||
let leaf = Leaf::Text { node: &node, content: &content, style_token: "body", wrap, max_lines };
|
|
||||||
CellMeasure.measure(&leaf, Constraint { known: [None, None], available: [room, Avail::MaxContent] })
|
|
||||||
}
|
|
||||||
|
|
||||||
fn layout_lines(text: &str, wrap: bool, max_lines: Option<u32>, width: f32) -> Vec<String> {
|
|
||||||
let node = NodeId::new("n");
|
|
||||||
let request = TextRequest { node: &node, text, style_token: "body", wrap, max_lines };
|
|
||||||
CellMeasure
|
|
||||||
.text(&request, width)
|
|
||||||
.lines
|
|
||||||
.into_iter()
|
|
||||||
.enumerate()
|
|
||||||
.map(|(row, line)| {
|
|
||||||
assert_eq!((line.y, line.height), (row as f32, 1.0));
|
|
||||||
match line.run {
|
|
||||||
Run::Cells { text, .. } => text.as_str().to_string(),
|
|
||||||
other => panic!("{other:?}"),
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn lines(text: &str, width: u32) -> Vec<String> {
|
|
||||||
layout_lines(text, true, None, width as f32)
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn wrap_table() {
|
|
||||||
assert_eq!(lines("hello world", 5), ["hello", "world"]);
|
|
||||||
assert_eq!(lines("hello world", 11), ["hello world"]);
|
|
||||||
let han = "\u{4e2d}\u{6587}\u{6587}\u{5b57}";
|
|
||||||
assert_eq!(lines(han, 5), ["\u{4e2d}\u{6587}", "\u{6587}\u{5b57}"]);
|
|
||||||
assert_eq!(lines(han, 3).len(), 4);
|
|
||||||
assert_eq!(lines("\u{4e2d}", 1), ["\u{4e2d}"]);
|
|
||||||
assert_eq!(leaf_measure("\u{4e2d}", true, None, Avail::Definite(1.0)), (2.0, 1.0));
|
|
||||||
assert_eq!(lines("abcdefgh", 3), ["abc", "def", "gh"]);
|
|
||||||
assert_eq!(layout_lines("a\nb", false, None, 80.0), ["a", "b"]);
|
|
||||||
assert_eq!(layout_lines("a\r\nb\u{2028}c", true, None, 80.0), ["a", "b", "c"]);
|
|
||||||
assert_eq!(layout_lines("a\nb", true, Some(1), 80.0), ["a"]);
|
|
||||||
assert_eq!(lines("hello world", 5), ["hello", "world"]);
|
|
||||||
assert_eq!(lines("", 5), [""]);
|
|
||||||
assert_eq!(lines("a\n\nb", 5), ["a", "", "b"]);
|
|
||||||
assert_eq!(lines("a\n", 5), ["a"]);
|
|
||||||
// A break opportunity that falls before a dropped mark (LRM here) is kept for the next cluster.
|
|
||||||
assert_eq!(lines("a \u{200e}bcd", 3), ["a", "bcd"]);
|
|
||||||
// A cluster never splits, however narrow the room.
|
|
||||||
assert_eq!(lines("\u{1f468}\u{200d}\u{1f469}", 1), ["\u{1f468}\u{200d}\u{1f469}"]);
|
|
||||||
assert_eq!(lines("e\u{301}e\u{301}", 1), ["e\u{301}", "e\u{301}"]);
|
|
||||||
assert_eq!(leaf_measure("hello world", true, None, Avail::MinContent).0, 5.0);
|
|
||||||
assert_eq!(leaf_measure("a\nbcd", true, None, Avail::MaxContent).0, 3.0);
|
|
||||||
assert_eq!(leaf_measure("a\nbcd", false, None, Avail::MinContent), (3.0, 2.0));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn measure_agrees_with_text() {
|
|
||||||
let rows: &[(&str, bool, Option<u32>, u32)] = &[
|
|
||||||
("hello world", true, None, 5),
|
|
||||||
("hello world", true, None, 11),
|
|
||||||
("\u{4e2d}\u{6587}\u{6587}\u{5b57}", true, None, 5),
|
|
||||||
("\u{4e2d}\u{6587}\u{6587}\u{5b57}", true, None, 3),
|
|
||||||
("\u{4e2d}", true, None, 1),
|
|
||||||
("abcdefgh", true, None, 3),
|
|
||||||
("a\nb", false, None, 80),
|
|
||||||
("a\nb", true, Some(1), 80),
|
|
||||||
("one two three\tfour five", true, Some(3), 7),
|
|
||||||
("\u{1f469}\u{200d}\u{1f469} x \u{1f600}\u{1f600}\u{1f600}", true, None, 4),
|
|
||||||
("", true, None, 4),
|
|
||||||
];
|
|
||||||
for &(text, wrap, max_lines, width) in rows {
|
|
||||||
let laid = layout_lines(text, wrap, max_lines, width as f32);
|
|
||||||
let (w, h) = leaf_measure(text, wrap, max_lines, Avail::Definite(width as f32));
|
|
||||||
let widest = laid.iter().map(|l| CellText::new(l).width()).max().unwrap_or(0);
|
|
||||||
assert_eq!((w, h), (widest as f32, laid.len() as f32), "{text:?} at {width}");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn controls_have_shipped_sizes() {
|
|
||||||
let node = NodeId::new("n");
|
|
||||||
let text = Bound::Text(String::new());
|
|
||||||
let c = Constraint { known: [None, None], available: [Avail::MaxContent, Avail::MaxContent] };
|
|
||||||
let mut m = CellMeasure;
|
|
||||||
assert_eq!(m.measure(&Leaf::TextInput { node: &node, multiline: false, placeholder: &text, value: &text }, c), (25.0, 1.0));
|
|
||||||
assert_eq!(m.measure(&Leaf::TextInput { node: &node, multiline: true, placeholder: &text, value: &text }, c), (25.0, 3.0));
|
|
||||||
assert_eq!(m.measure(&Leaf::Toggle { node: &node }, c), (5.0, 1.0));
|
|
||||||
assert_eq!(m.measure(&Leaf::Slider { node: &node }, c), (20.0, 1.0));
|
|
||||||
assert_eq!(m.measure(&Leaf::Select { node: &node, selected: &text }, c), (20.0, 1.0));
|
|
||||||
assert_eq!(m.measure(&Leaf::Image { node: &node, asset: &Bound::Absent }, c), (0.0, 0.0));
|
|
||||||
let entry = AssetEntry { id: "a".into(), media_type: "image/png".into(), uri: "asset://a".into(), width: count(17), height: count(33) };
|
|
||||||
assert_eq!(m.measure(&Leaf::Image { node: &node, asset: &Bound::Asset(entry) }, c), (3.0, 3.0), "extent over (8, 16), rounded up");
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Random strings, every control among them, never panic and never put a control character into
|
|
||||||
/// any line at any width.
|
|
||||||
#[test]
|
|
||||||
fn fuzz_never_emits_a_control() {
|
|
||||||
let mut seed = 0x9e37_79b9_7f4a_7c15_u64;
|
|
||||||
let mut next = move || {
|
|
||||||
seed ^= seed << 13;
|
|
||||||
seed ^= seed >> 7;
|
|
||||||
seed ^= seed << 17;
|
|
||||||
seed
|
|
||||||
};
|
|
||||||
let pool: Vec<char> = (0u32..0x20)
|
|
||||||
.chain(0x7f..0xa0)
|
|
||||||
.chain([0x2028, 0x2029, 0x200b, 0x200d, 0xfe0f, 0x301, 0x20, 0x9, 0x4e2d, 0x1f600, 0x1f469, 0x1f3fd, 0x202c, 0x1f1ef, 0x1f1f5, 0x600, 0x20e3])
|
|
||||||
.filter_map(char::from_u32)
|
|
||||||
.collect();
|
|
||||||
for round in 0..400_000 {
|
|
||||||
let text: String = if round % 4 == 0 {
|
|
||||||
// Raw bytes, so truncated and surrogate encodings become U+FFFD.
|
|
||||||
let bytes: Vec<u8> = (0..(next() % 40)).map(|_| next() as u8).collect();
|
|
||||||
String::from_utf8_lossy(&bytes).into_owned()
|
|
||||||
} else {
|
|
||||||
(0..(next() % 40))
|
|
||||||
.map(|_| match next() % 3 {
|
|
||||||
0 => pool[(next() % pool.len() as u64) as usize],
|
|
||||||
1 => char::from_u32((next() % 0x30000) as u32).unwrap_or('\u{fffd}'),
|
|
||||||
_ => char::from(b'a' + (next() % 26) as u8),
|
|
||||||
})
|
|
||||||
.collect()
|
|
||||||
};
|
|
||||||
let width = (next() % 12) as f32;
|
|
||||||
let wrap = next() % 2 == 0;
|
|
||||||
for line in layout_lines(&text, wrap, None, width) {
|
|
||||||
assert!(!line.chars().any(|c| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}')), "{text:?} -> {line:?}");
|
|
||||||
}
|
|
||||||
// What is emitted measures to what was recorded: measuring it again changes nothing.
|
|
||||||
let node = NodeId::new("n");
|
|
||||||
let request = TextRequest { node: &node, text: &text, style_token: "body", wrap, max_lines: None };
|
|
||||||
for line in CellMeasure.text(&request, width).lines {
|
|
||||||
let Run::Cells { text: emitted, .. } = line.run else { panic!() };
|
|
||||||
assert_eq!(CellText::new(emitted.as_str()), emitted, "{text:?} at {width}");
|
|
||||||
assert!(emitted.clusters().all(|(_, w)| w >= 1));
|
|
||||||
}
|
|
||||||
let lone = CellText::new(&text);
|
|
||||||
assert_eq!(CellText::new(lone.as_str()), lone, "{text:?}");
|
|
||||||
let _ = leaf_measure(&text, wrap, Some(3), Avail::Definite(width));
|
|
||||||
let _ = leaf_measure(&text, wrap, None, Avail::MinContent);
|
|
||||||
assert!(!CellText::new(&text).as_str().chars().any(|c| c.is_control()));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,490 +0,0 @@
|
||||||
//! The frame entry: Core::frame equals the stages composed by hand, and keeps its promises
|
|
||||||
//! about the port, the last good frame and the room it is given.
|
|
||||||
|
|
||||||
use thing_contract::*;
|
|
||||||
use thing_core::bind::Binder;
|
|
||||||
use thing_core::diagnostic::Code;
|
|
||||||
use thing_core::input::{InputEvent, Key, Modifiers, PointerButton, WheelUnit};
|
|
||||||
use thing_core::layout::{LayoutFrame, Metrics, layout};
|
|
||||||
use thing_core::port::{Address, Ledger};
|
|
||||||
use thing_core::render::{RenderCommand, RenderInput, ScrollOffsets, 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]);
|
|
||||||
}
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
# thing-core goldens
|
|
||||||
|
|
||||||
`resolve-*.bin` is a CultCache single-file store holding one resolved surface document under the
|
|
||||||
pinned clock; `resolve-*.txt` is the `{:#?}` text of the same document. The binary is the oracle and
|
|
||||||
the text is compared beside it. `THING_BLESS=1` through `thing_testkit::golden::check_with_text` is
|
|
||||||
the only way either changes.
|
|
||||||
|
|
@ -1,14 +0,0 @@
|
||||||
load visible bool true
|
|
||||||
load content text "42.0%"
|
|
||||||
minds visible bool true
|
|
||||||
minds#6:mind-1/mind-name visible bool true
|
|
||||||
minds#6:mind-1/mind-name content text "Eureka"
|
|
||||||
minds#6:mind-2/mind-name visible bool true
|
|
||||||
minds#6:mind-2/mind-name content text "Libby"
|
|
||||||
minds#6:mind-3/mind-name visible bool true
|
|
||||||
minds#6:mind-3/mind-name content text "Kiko"
|
|
||||||
restart visible bool true
|
|
||||||
restart enabled bool true
|
|
||||||
restart-label visible bool true
|
|
||||||
restart-label content text "Restart"
|
|
||||||
root visible bool true
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
enabled visible bool true
|
|
||||||
enabled checked bool true
|
|
||||||
port visible bool true
|
|
||||||
port placeholder text "port"
|
|
||||||
port initial text "8080"
|
|
||||||
root visible bool true
|
|
||||||
theme visible bool true
|
|
||||||
theme selected text "dark"
|
|
||||||
theme options options [dark=Dark, light=Light]
|
|
||||||
volume visible bool true
|
|
||||||
volume value number 40
|
|
||||||
|
|
@ -1,8 +0,0 @@
|
||||||
surface thing:surface:provider.swarm.dashboard viewport 100x37 scale 1 cells
|
|
||||||
root 0 0 100 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
|
|
||||||
|
|
@ -1,8 +0,0 @@
|
||||||
surface thing:surface:provider.swarm.dashboard viewport 800x600 scale 1.5 pixels
|
|
||||||
root 0 0 1200 102
|
|
||||||
load 3 3 597 24
|
|
||||||
minds#6:mind-1/mind-name 606 3 597 24
|
|
||||||
minds#6:mind-2/mind-name 3 39 597 24
|
|
||||||
minds#6:mind-3/mind-name 606 39 597 24
|
|
||||||
restart 3 75 597 24
|
|
||||||
restart-label 3 75 84 24
|
|
||||||
|
|
@ -1,8 +0,0 @@
|
||||||
surface thing:surface:provider.swarm.dashboard viewport 800x600 scale 2 pixels
|
|
||||||
root 0 0 1600 136
|
|
||||||
load 4 4 796 32
|
|
||||||
minds#6:mind-1/mind-name 808 4 796 32
|
|
||||||
minds#6:mind-2/mind-name 4 52 796 32
|
|
||||||
minds#6:mind-3/mind-name 808 52 796 32
|
|
||||||
restart 4 100 796 32
|
|
||||||
restart-label 4 100 112 32
|
|
||||||
|
|
@ -1,8 +0,0 @@
|
||||||
surface thing:surface:provider.swarm.dashboard viewport 800x600 scale 1 pixels
|
|
||||||
root 0 0 800 68
|
|
||||||
load 2 2 398 16
|
|
||||||
minds#6:mind-1/mind-name 404 2 398 16
|
|
||||||
minds#6:mind-2/mind-name 2 26 398 16
|
|
||||||
minds#6:mind-3/mind-name 404 26 398 16
|
|
||||||
restart 2 50 398 16
|
|
||||||
restart-label 2 50 56 16
|
|
||||||
|
|
@ -1,5 +0,0 @@
|
||||||
surface thing:surface:provider.login.login viewport 800x600 scale 1 pixels
|
|
||||||
root 0 0 800 52
|
|
||||||
username 2 2 796 24
|
|
||||||
sign-in-button 2 34 796 16
|
|
||||||
sign-in-button-label 2 34 56 16
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue