Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 17a0008d3e | |||
| f532f6bb6a | |||
| 668ec478cd | |||
| 7388984450 | |||
| 8ca1bab380 | |||
| 63ed2e3b01 | |||
| 1033d30728 | |||
| c59a223e6c | |||
| 8fe8b1aaad | |||
| 9da9080f8a | |||
| 72d93006d0 | |||
| 6f0cc63188 | |||
| 2c08d99992 | |||
| 5a11b23c4e | |||
| d9b09ee5f4 | |||
| 491fc2020f | |||
| b1c007d8b1 | |||
| edeeee2129 | |||
| e16a8eb917 | |||
| 4d254a1adf | |||
| 31f324f738 | |||
| d052428094 | |||
| 7654e27364 | |||
| 159ad486e5 | |||
|
|
b6e06cf89a | ||
|
|
366774dc4c | ||
|
|
9eb099be4d | ||
|
|
3136ee8b80 | ||
| fd7a48484d | |||
| 4a6c04a073 | |||
|
|
ee8eec41f3 | ||
|
|
ebafda432f | ||
|
|
e95f1ab5ba |
240 changed files with 42729 additions and 144 deletions
1
.cargo/mutants.toml
Normal file
1
.cargo/mutants.toml
Normal file
|
|
@ -0,0 +1 @@
|
||||||
|
test_workspace = true
|
||||||
35
.github/workflows/portable-contracts.yml
vendored
35
.github/workflows/portable-contracts.yml
vendored
|
|
@ -8,6 +8,11 @@ on:
|
||||||
pull_request:
|
pull_request:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
# A newer push or PR update replaces the older run on the same ref; workflow_dispatch runs are never cancelled.
|
||||||
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
|
cancel-in-progress: ${{ github.event_name != 'workflow_dispatch' }}
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
contracts-and-browser:
|
contracts-and-browser:
|
||||||
name: ${{ matrix.os }} ${{ matrix.package }}
|
name: ${{ matrix.os }} ${{ matrix.package }}
|
||||||
|
|
@ -16,7 +21,10 @@ jobs:
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
os: [windows-latest, ubuntu-latest]
|
# No Windows runner exists: the windows-latest leg runs on workflow_dispatch only (GitHub or a
|
||||||
|
# Windows runner), the ubuntu-latest leg gates push and PR. Windows push/PR triggers return in the PR
|
||||||
|
# that registers a Windows runner.
|
||||||
|
os: ${{ fromJSON(github.event_name == 'workflow_dispatch' && '["windows-latest", "ubuntu-latest"]' || '["ubuntu-latest"]') }}
|
||||||
package: [eve-contracts, eve-browser-lowering]
|
package: [eve-contracts, eve-browser-lowering]
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
|
|
@ -30,6 +38,14 @@ jobs:
|
||||||
cache: npm
|
cache: npm
|
||||||
cache-dependency-path: packages/${{ matrix.package }}/package-lock.json
|
cache-dependency-path: packages/${{ matrix.package }}/package-lock.json
|
||||||
|
|
||||||
|
# eve-browser-lowering links eve-contracts as file:../eve-contracts; npm installs none of the
|
||||||
|
# linked package's dependencies, and tsc resolves its declarations from the real path, so
|
||||||
|
# ajv must be installed in eve-contracts itself.
|
||||||
|
- name: Install eve-contracts dependencies
|
||||||
|
if: matrix.package != 'eve-contracts'
|
||||||
|
working-directory: packages/eve-contracts
|
||||||
|
run: npm ci
|
||||||
|
|
||||||
- name: Install package dependencies
|
- name: Install package dependencies
|
||||||
working-directory: packages/${{ matrix.package }}
|
working-directory: packages/${{ matrix.package }}
|
||||||
run: npm ci
|
run: npm ci
|
||||||
|
|
@ -38,6 +54,23 @@ jobs:
|
||||||
working-directory: packages/${{ matrix.package }}
|
working-directory: packages/${{ matrix.package }}
|
||||||
run: npm test
|
run: npm test
|
||||||
|
|
||||||
|
# The forge runner images carry no pwsh; GitHub's Windows and hosted images do.
|
||||||
|
- name: Install PowerShell
|
||||||
|
if: runner.os == 'Linux'
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
if command -v pwsh >/dev/null; then pwsh -Version; exit 0; fi
|
||||||
|
SUDO=""; [ "$(id -u)" -eq 0 ] || SUDO="sudo"
|
||||||
|
PWSH_VERSION=7.4.6
|
||||||
|
curl -fsSL "https://github.com/PowerShell/PowerShell/releases/download/v${PWSH_VERSION}/powershell-${PWSH_VERSION}-linux-x64.tar.gz" -o "${RUNNER_TEMP:-/tmp}/powershell.tar.gz"
|
||||||
|
$SUDO mkdir -p /opt/microsoft/powershell/7
|
||||||
|
$SUDO tar -xzf "${RUNNER_TEMP:-/tmp}/powershell.tar.gz" -C /opt/microsoft/powershell/7
|
||||||
|
$SUDO chmod +x /opt/microsoft/powershell/7/pwsh
|
||||||
|
$SUDO ln -sf /opt/microsoft/powershell/7/pwsh /usr/local/bin/pwsh
|
||||||
|
echo "DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1" >> "$GITHUB_ENV"
|
||||||
|
DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=1 pwsh -Version
|
||||||
|
|
||||||
- name: Reject stale generated output
|
- name: Reject stale generated output
|
||||||
shell: pwsh
|
shell: pwsh
|
||||||
run: |
|
run: |
|
||||||
|
|
|
||||||
7
.gitignore
vendored
7
.gitignore
vendored
|
|
@ -8,12 +8,19 @@ packages/eve-browser-lowering/node_modules/
|
||||||
!packages/eve-contracts/**
|
!packages/eve-contracts/**
|
||||||
packages/eve-contracts/node_modules/
|
packages/eve-contracts/node_modules/
|
||||||
packages/eve-contracts/*.tgz
|
packages/eve-contracts/*.tgz
|
||||||
|
!packages/thing-contract/
|
||||||
|
!packages/thing-contract/**
|
||||||
|
packages/thing-contract/node_modules/
|
||||||
|
packages/thing-contract/dist/
|
||||||
|
packages/thing-contract/dist-test/
|
||||||
!packages/org.gamecult.eve.surface/
|
!packages/org.gamecult.eve.surface/
|
||||||
!packages/org.gamecult.eve.surface/**
|
!packages/org.gamecult.eve.surface/**
|
||||||
packages/org.gamecult.eve.surface/bin~/
|
packages/org.gamecult.eve.surface/bin~/
|
||||||
packages/org.gamecult.eve.surface/obj~/
|
packages/org.gamecult.eve.surface/obj~/
|
||||||
!packages/org.gamecult.eve.unity-uitoolkit/
|
!packages/org.gamecult.eve.unity-uitoolkit/
|
||||||
!packages/org.gamecult.eve.unity-uitoolkit/**
|
!packages/org.gamecult.eve.unity-uitoolkit/**
|
||||||
|
!packages/GameCult.Thing.Contract/
|
||||||
|
!packages/GameCult.Thing.Contract/**
|
||||||
obj/
|
obj/
|
||||||
artifacts/
|
artifacts/
|
||||||
tools/deps/
|
tools/deps/
|
||||||
|
|
|
||||||
415
Cargo.lock
generated
415
Cargo.lock
generated
|
|
@ -17,12 +17,36 @@ version = "1.0.104"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ar_archive_writer"
|
||||||
|
version = "0.5.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "523e5e187fff36fcb8d1d19ccf0ca4ca43ec3d158316057f66dc6f72716bc5ec"
|
||||||
|
dependencies = [
|
||||||
|
"object",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "autocfg"
|
name = "autocfg"
|
||||||
version = "1.5.1"
|
version = "1.5.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bitflags"
|
||||||
|
version = "2.13.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "block-buffer"
|
||||||
|
version = "0.10.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||||
|
dependencies = [
|
||||||
|
"generic-array",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bumpalo"
|
name = "bumpalo"
|
||||||
version = "3.20.3"
|
version = "3.20.3"
|
||||||
|
|
@ -65,10 +89,55 @@ version = "0.8.7"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
|
checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cpufeatures"
|
||||||
|
version = "0.2.17"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "crossterm"
|
||||||
|
version = "0.29.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d8b9f2e4c67f833b660cdb0a3523065869fb35570177239812ed4c905aeff87b"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags",
|
||||||
|
"crossterm_winapi",
|
||||||
|
"document-features",
|
||||||
|
"mio",
|
||||||
|
"parking_lot",
|
||||||
|
"rustix",
|
||||||
|
"signal-hook",
|
||||||
|
"signal-hook-mio",
|
||||||
|
"winapi",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "crossterm_winapi"
|
||||||
|
version = "0.9.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b"
|
||||||
|
dependencies = [
|
||||||
|
"winapi",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "crypto-common"
|
||||||
|
version = "0.1.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||||
|
dependencies = [
|
||||||
|
"generic-array",
|
||||||
|
"typenum",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cultcache-rs"
|
name = "cultcache-rs"
|
||||||
version = "0.2.0"
|
version = "0.3.1"
|
||||||
source = "git+https://github.com/GameCult/CultLib.git?rev=b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7#b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7"
|
source = "git+https://github.com/GameCult/CultLib.git?rev=4c9af401ae33812d862dde4ff3131433fc73c7dc#4c9af401ae33812d862dde4ff3131433fc73c7dc"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"chrono",
|
"chrono",
|
||||||
|
|
@ -79,20 +148,52 @@ dependencies = [
|
||||||
"serde",
|
"serde",
|
||||||
"serde_bytes",
|
"serde_bytes",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
"serde_stacker",
|
||||||
|
"sha2",
|
||||||
|
"stacker",
|
||||||
"uuid",
|
"uuid",
|
||||||
"windows-sys",
|
"windows-sys 0.59.0",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cultcache-rs-derive"
|
name = "cultcache-rs-derive"
|
||||||
version = "0.1.0"
|
version = "0.2.0"
|
||||||
source = "git+https://github.com/GameCult/CultLib.git?rev=b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7#b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7"
|
source = "git+https://github.com/GameCult/CultLib.git?rev=4c9af401ae33812d862dde4ff3131433fc73c7dc#4c9af401ae33812d862dde4ff3131433fc73c7dc"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"proc-macro2",
|
"proc-macro2",
|
||||||
"quote",
|
"quote",
|
||||||
"syn 2.0.119",
|
"syn 2.0.119",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "digest"
|
||||||
|
version = "0.10.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||||
|
dependencies = [
|
||||||
|
"block-buffer",
|
||||||
|
"crypto-common",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "document-features"
|
||||||
|
version = "0.2.12"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61"
|
||||||
|
dependencies = [
|
||||||
|
"litrs",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "errno"
|
||||||
|
version = "0.3.15"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"windows-sys 0.61.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "find-msvc-tools"
|
name = "find-msvc-tools"
|
||||||
version = "0.1.14"
|
version = "0.1.14"
|
||||||
|
|
@ -133,6 +234,16 @@ dependencies = [
|
||||||
"slab",
|
"slab",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "generic-array"
|
||||||
|
version = "0.14.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||||
|
dependencies = [
|
||||||
|
"typenum",
|
||||||
|
"version_check",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "getrandom"
|
name = "getrandom"
|
||||||
version = "0.4.3"
|
version = "0.4.3"
|
||||||
|
|
@ -191,6 +302,27 @@ version = "0.2.190"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
|
checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "linux-raw-sys"
|
||||||
|
version = "0.12.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "litrs"
|
||||||
|
version = "1.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "02b614978e47ce529faee66579f2b2fe19c94aa96d910a6a9a8043b2b02d8175"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "lock_api"
|
||||||
|
version = "0.4.14"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
|
||||||
|
dependencies = [
|
||||||
|
"scopeguard",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "log"
|
name = "log"
|
||||||
version = "0.4.34"
|
version = "0.4.34"
|
||||||
|
|
@ -203,6 +335,18 @@ version = "2.8.3"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "mio"
|
||||||
|
version = "1.2.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"log",
|
||||||
|
"wasi",
|
||||||
|
"windows-sys 0.61.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "num-traits"
|
name = "num-traits"
|
||||||
version = "0.2.19"
|
version = "0.2.19"
|
||||||
|
|
@ -212,12 +356,44 @@ dependencies = [
|
||||||
"autocfg",
|
"autocfg",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "object"
|
||||||
|
version = "0.39.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b"
|
||||||
|
dependencies = [
|
||||||
|
"memchr",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "once_cell"
|
name = "once_cell"
|
||||||
version = "1.21.4"
|
version = "1.21.4"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "parking_lot"
|
||||||
|
version = "0.12.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
|
||||||
|
dependencies = [
|
||||||
|
"lock_api",
|
||||||
|
"parking_lot_core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "parking_lot_core"
|
||||||
|
version = "0.9.12"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"libc",
|
||||||
|
"redox_syscall",
|
||||||
|
"smallvec",
|
||||||
|
"windows-link",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pin-project-lite"
|
name = "pin-project-lite"
|
||||||
version = "0.2.17"
|
version = "0.2.17"
|
||||||
|
|
@ -233,6 +409,16 @@ dependencies = [
|
||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "psm"
|
||||||
|
version = "0.1.32"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622"
|
||||||
|
dependencies = [
|
||||||
|
"ar_archive_writer",
|
||||||
|
"cc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "quote"
|
name = "quote"
|
||||||
version = "1.0.47"
|
version = "1.0.47"
|
||||||
|
|
@ -257,6 +443,15 @@ dependencies = [
|
||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "redox_syscall"
|
||||||
|
version = "0.5.18"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rmp"
|
name = "rmp"
|
||||||
version = "0.8.15"
|
version = "0.8.15"
|
||||||
|
|
@ -276,12 +471,37 @@ dependencies = [
|
||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rustc-hash"
|
||||||
|
version = "2.1.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rustix"
|
||||||
|
version = "1.1.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags",
|
||||||
|
"errno",
|
||||||
|
"libc",
|
||||||
|
"linux-raw-sys",
|
||||||
|
"windows-sys 0.61.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rustversion"
|
name = "rustversion"
|
||||||
version = "1.0.23"
|
version = "1.0.23"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "scopeguard"
|
||||||
|
version = "1.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "serde"
|
name = "serde"
|
||||||
version = "1.0.229"
|
version = "1.0.229"
|
||||||
|
|
@ -335,18 +555,99 @@ dependencies = [
|
||||||
"zmij",
|
"zmij",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde_stacker"
|
||||||
|
version = "0.1.14"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d4936375d50c4be7eff22293a9344f8e46f323ed2b3c243e52f89138d9bb0f4a"
|
||||||
|
dependencies = [
|
||||||
|
"serde",
|
||||||
|
"serde_core",
|
||||||
|
"stacker",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "sha2"
|
||||||
|
version = "0.10.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"cpufeatures",
|
||||||
|
"digest",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "shlex"
|
name = "shlex"
|
||||||
version = "2.0.1"
|
version = "2.0.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "signal-hook"
|
||||||
|
version = "0.3.18"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"signal-hook-registry",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "signal-hook-mio"
|
||||||
|
version = "0.2.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"mio",
|
||||||
|
"signal-hook",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "signal-hook-registry"
|
||||||
|
version = "1.4.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"
|
||||||
|
dependencies = [
|
||||||
|
"errno",
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "slab"
|
name = "slab"
|
||||||
version = "0.4.12"
|
version = "0.4.12"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "slotmap"
|
||||||
|
version = "1.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038"
|
||||||
|
dependencies = [
|
||||||
|
"version_check",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "smallvec"
|
||||||
|
version = "1.16.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "stacker"
|
||||||
|
version = "0.1.25"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
"cfg-if",
|
||||||
|
"libc",
|
||||||
|
"psm",
|
||||||
|
"windows-sys 0.61.2",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "syn"
|
name = "syn"
|
||||||
version = "2.0.119"
|
version = "2.0.119"
|
||||||
|
|
@ -369,6 +670,18 @@ dependencies = [
|
||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "taffy"
|
||||||
|
version = "0.16.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cae92eb1b204bfd239b5c463e1bd2c3ce4913d2d3abfb5c64f5cfee9d65e5c68"
|
||||||
|
dependencies = [
|
||||||
|
"rustc-hash",
|
||||||
|
"serde",
|
||||||
|
"slotmap",
|
||||||
|
"smallvec",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "thing-contract"
|
name = "thing-contract"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
|
|
@ -378,14 +691,85 @@ dependencies = [
|
||||||
"rmp-serde",
|
"rmp-serde",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_bytes",
|
"serde_bytes",
|
||||||
|
"thing-testkit",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "thing-core"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"stacker",
|
||||||
|
"taffy",
|
||||||
|
"thing-contract",
|
||||||
|
"thing-testkit",
|
||||||
|
"unicode-linebreak",
|
||||||
|
"unicode-segmentation",
|
||||||
|
"unicode-width",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "thing-state"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"cultcache-rs",
|
||||||
|
"rmp-serde",
|
||||||
|
"serde",
|
||||||
|
"thing-core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "thing-testkit"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"anyhow",
|
||||||
|
"cultcache-rs",
|
||||||
|
"rmp-serde",
|
||||||
|
"serde",
|
||||||
|
"thing-contract",
|
||||||
|
"thing-core",
|
||||||
|
"thing-state",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "thing-tui"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"crossterm",
|
||||||
|
"thing-contract",
|
||||||
|
"thing-core",
|
||||||
|
"thing-testkit",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "typenum"
|
||||||
|
version = "1.20.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "unicode-ident"
|
name = "unicode-ident"
|
||||||
version = "1.0.26"
|
version = "1.0.26"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
|
checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unicode-linebreak"
|
||||||
|
version = "0.1.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unicode-segmentation"
|
||||||
|
version = "1.13.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unicode-width"
|
||||||
|
version = "0.2.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "uuid"
|
name = "uuid"
|
||||||
version = "1.28.0"
|
version = "1.28.0"
|
||||||
|
|
@ -397,6 +781,18 @@ dependencies = [
|
||||||
"wasm-bindgen",
|
"wasm-bindgen",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "version_check"
|
||||||
|
version = "0.9.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "wasi"
|
||||||
|
version = "0.11.1+wasi-snapshot-preview1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "wasm-bindgen"
|
name = "wasm-bindgen"
|
||||||
version = "0.2.129"
|
version = "0.2.129"
|
||||||
|
|
@ -532,6 +928,15 @@ dependencies = [
|
||||||
"windows-targets",
|
"windows-targets",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-sys"
|
||||||
|
version = "0.61.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
||||||
|
dependencies = [
|
||||||
|
"windows-link",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "windows-targets"
|
name = "windows-targets"
|
||||||
version = "0.52.6"
|
version = "0.52.6"
|
||||||
|
|
|
||||||
|
|
@ -4,6 +4,12 @@ resolver = "2"
|
||||||
|
|
||||||
[workspace.dependencies]
|
[workspace.dependencies]
|
||||||
anyhow = "1"
|
anyhow = "1"
|
||||||
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "b3bd8dd5e5b208b2012392e9c5d6dfee2441aaa7", package = "cultcache-rs" }
|
cultcache-rs = { git = "https://github.com/GameCult/CultLib.git", rev = "4c9af401ae33812d862dde4ff3131433fc73c7dc", package = "cultcache-rs" }
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
rmp-serde = "1.3"
|
rmp-serde = "1.3"
|
||||||
|
taffy = { version = "0.16", default-features = false, features = ["std", "taffy_tree", "flexbox", "grid", "block_layout", "content_size"] }
|
||||||
|
# The terminal text tables, pinned exactly: a width is a golden. unicode-width drops its cjk
|
||||||
|
# tables, so ambiguous width is narrow.
|
||||||
|
unicode-width = { version = "=0.2.3", default-features = false }
|
||||||
|
unicode-segmentation = "=1.13.3"
|
||||||
|
unicode-linebreak = "=0.1.5"
|
||||||
|
|
|
||||||
|
|
@ -12,4 +12,5 @@ serde = { workspace = true }
|
||||||
serde_bytes = "0.11"
|
serde_bytes = "0.11"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
|
thing-testkit = { path = "../thing-testkit" }
|
||||||
rmp-serde = { workspace = true }
|
rmp-serde = { workspace = true }
|
||||||
|
|
|
||||||
|
|
@ -28,7 +28,7 @@ pub struct AssetCatalog {
|
||||||
pub catalog_id: Segment,
|
pub catalog_id: Segment,
|
||||||
#[cultcache(key = 2)]
|
#[cultcache(key = 2)]
|
||||||
pub version: Version,
|
pub version: Version,
|
||||||
#[cultcache(key = 3)]
|
#[cultcache(key = 3, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.AssetEntry>")]
|
||||||
pub assets: Vec<AssetEntry>,
|
pub assets: Vec<AssetEntry>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -37,6 +37,7 @@ pub enum CommandRef {
|
||||||
|
|
||||||
/// A typed record of the declared `payload_schema`, as its MessagePack bytes.
|
/// A typed record of the declared `payload_schema`, as its MessagePack bytes.
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||||
|
#[cultcache(type_name = "GameCult.Thing.Contract.RecordPayload")]
|
||||||
pub struct RecordPayload {
|
pub struct RecordPayload {
|
||||||
#[cultcache(key = 0)]
|
#[cultcache(key = 0)]
|
||||||
pub schema: SchemaId,
|
pub schema: SchemaId,
|
||||||
|
|
@ -105,7 +106,7 @@ pub struct CommandInvocation {
|
||||||
pub command: CommandId,
|
pub command: CommandId,
|
||||||
#[cultcache(key = 4)]
|
#[cultcache(key = 4)]
|
||||||
pub payload: RecordPayload,
|
pub payload: RecordPayload,
|
||||||
#[cultcache(key = 5)]
|
#[cultcache(key = 5, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.CapturedInput>")]
|
||||||
pub captured: Vec<CapturedInput>,
|
pub captured: Vec<CapturedInput>,
|
||||||
#[cultcache(key = 6)]
|
#[cultcache(key = 6)]
|
||||||
pub client: String,
|
pub client: String,
|
||||||
|
|
@ -114,6 +115,14 @@ pub struct CommandInvocation {
|
||||||
pub issued_at: String,
|
pub issued_at: String,
|
||||||
#[cultcache(key = 8)]
|
#[cultcache(key = 8)]
|
||||||
pub delegation: Option<String>,
|
pub delegation: Option<String>,
|
||||||
|
/// The activating node's declared id in the resolved tree. For a node inside a Repeat it is
|
||||||
|
/// the template's id, never an instance id. A confirmed invocation names the node confirmed;
|
||||||
|
/// a resumed one carries the source and items of the invocation whose result carried the effect.
|
||||||
|
#[cultcache(key = 9)]
|
||||||
|
pub source: NodeId,
|
||||||
|
/// The key of each Repeat instance enclosing the source, outermost first; empty outside any Repeat.
|
||||||
|
#[cultcache(key = 10, type_name = "System.Collections.Immutable.ImmutableArray<System.String>")]
|
||||||
|
pub items: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CommandInvocation {
|
impl CommandInvocation {
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@
|
||||||
|
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
|
|
||||||
|
use cultcache_rs::CultTypeName;
|
||||||
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
|
use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
|
||||||
|
|
||||||
/// A value was outside its domain. Names the domain and its bound, never the value.
|
/// A value was outside its domain. Names the domain and its bound, never the value.
|
||||||
|
|
@ -72,6 +73,13 @@ impl std::error::Error for DomainError {}
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||||
pub struct Seq(i32);
|
pub struct Seq(i32);
|
||||||
|
|
||||||
|
impl CultTypeName for Seq {
|
||||||
|
fn cult_type_name() -> String {
|
||||||
|
"System.Int32".to_string()
|
||||||
|
}
|
||||||
|
const VALUE_TYPE: bool = true;
|
||||||
|
}
|
||||||
|
|
||||||
impl Seq {
|
impl Seq {
|
||||||
pub const FIRST: Seq = Seq(1);
|
pub const FIRST: Seq = Seq(1);
|
||||||
|
|
||||||
|
|
@ -108,6 +116,13 @@ impl Seq {
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||||
pub struct Version(i64);
|
pub struct Version(i64);
|
||||||
|
|
||||||
|
impl CultTypeName for Version {
|
||||||
|
fn cult_type_name() -> String {
|
||||||
|
"System.Int64".to_string()
|
||||||
|
}
|
||||||
|
const VALUE_TYPE: bool = true;
|
||||||
|
}
|
||||||
|
|
||||||
impl Version {
|
impl Version {
|
||||||
pub fn new(value: i64) -> Result<Self, DomainError> {
|
pub fn new(value: i64) -> Result<Self, DomainError> {
|
||||||
if value >= 0 { Ok(Self(value)) } else { Err(DomainError::new("Version", "at least 0")) }
|
if value >= 0 { Ok(Self(value)) } else { Err(DomainError::new("Version", "at least 0")) }
|
||||||
|
|
@ -166,6 +181,12 @@ impl Count {
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||||
pub struct Segment(String);
|
pub struct Segment(String);
|
||||||
|
|
||||||
|
impl CultTypeName for Segment {
|
||||||
|
fn cult_type_name() -> String {
|
||||||
|
"System.String".to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl Segment {
|
impl Segment {
|
||||||
pub fn new(value: impl Into<String>) -> Result<Self, DomainError> {
|
pub fn new(value: impl Into<String>) -> Result<Self, DomainError> {
|
||||||
let value = value.into();
|
let value = value.into();
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
//! Identifier newtypes and the record key of each kind. No caller spells a key as a free string.
|
//! Identifier newtypes and the record key of each kind. No caller spells a key as a free string.
|
||||||
|
|
||||||
|
use cultcache_rs::CultTypeName;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use crate::domain::{Segment, Seq, Version};
|
use crate::domain::{Segment, Seq, Version};
|
||||||
|
|
@ -20,6 +21,12 @@ macro_rules! id_type {
|
||||||
&self.0
|
&self.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl CultTypeName for $name {
|
||||||
|
fn cult_type_name() -> String {
|
||||||
|
"System.String".to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -65,6 +72,6 @@ pub(crate) fn result_key(invocation_id: &str, seq: Seq) -> String {
|
||||||
format!("thing:result:{invocation_id}.{}", seq.get())
|
format!("thing:result:{invocation_id}.{}", seq.get())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) fn asset_catalog_key(provider: &ProviderId, catalog_id: &Segment) -> String {
|
pub fn asset_catalog_key(provider: &ProviderId, catalog_id: &Segment) -> String {
|
||||||
format!("thing:asset_catalog:{}.{}", provider.as_str(), catalog_id.as_str())
|
format!("thing:asset_catalog:{}.{}", provider.as_str(), catalog_id.as_str())
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -9,10 +9,11 @@
|
||||||
//! field types (`Seq`, `Version`, `Count`, `Segment`), whose `Deserialize` calls the same
|
//! field types (`Seq`, `Version`, `Count`, `Segment`), whose `Deserialize` calls the same
|
||||||
//! `new` the constructors call, so no door skips a check.
|
//! `new` the constructors call, so no door skips a check.
|
||||||
//!
|
//!
|
||||||
//! Hazard: decoding these kinds from untrusted bytes on a default-size thread can abort the
|
//! Stack hazard: `Node` nests without a bound of its own, and serde's `Deserialize` recurses
|
||||||
//! process inside CultCache's nesting bound before the bound refuses (the stack is not
|
//! once per level, so a hostile payload nested deep enough overflows the stack of a caller that
|
||||||
//! bounded by nesting depth). The owner is `cultlib-gaps:follow_up:decode-stack-safety`; the
|
//! decodes it directly. CultCache refuses such a payload on read and on write
|
||||||
//! tests decode on a 16 MiB thread until it lands.
|
//! (`cultcache_rs::check_payload_depth`, 256 containers); a caller that decodes bytes outside a
|
||||||
|
//! CultCache must run that check first.
|
||||||
|
|
||||||
mod asset;
|
mod asset;
|
||||||
mod command;
|
mod command;
|
||||||
|
|
@ -26,12 +27,20 @@ mod style;
|
||||||
pub use asset::*;
|
pub use asset::*;
|
||||||
pub use command::*;
|
pub use command::*;
|
||||||
pub use domain::{Count, DomainError, Segment, Seq, Version};
|
pub use domain::{Count, DomainError, Segment, Seq, Version};
|
||||||
pub use keys::{CommandId, NodeId, ProviderId, RecordKey, SchemaId};
|
pub use keys::{CommandId, NodeId, ProviderId, RecordKey, SchemaId, asset_catalog_key};
|
||||||
pub use node::*;
|
pub use node::*;
|
||||||
pub use result::*;
|
pub use result::*;
|
||||||
pub use source::*;
|
pub use source::*;
|
||||||
pub use style::*;
|
pub use style::*;
|
||||||
|
|
||||||
|
pub use cultcache_rs::DatabaseEntry;
|
||||||
|
|
||||||
|
/// Whether `text` is an RFC 3339 UTC-or-offset date-time of the one shape a Thing timestamp is
|
||||||
|
/// written in (`YYYY-MM-DDThh:mm:ss`, an optional fraction, then `Z` or an offset). A timestamp a
|
||||||
|
/// provider publishes as text is shown as written only when this accepts it.
|
||||||
|
pub fn is_timestamp_text(text: &str) -> bool {
|
||||||
|
cultcache_rs::is_stored_at_stamp(text)
|
||||||
|
}
|
||||||
use cultcache_rs::{CultCache, CultCacheRegistry};
|
use cultcache_rs::{CultCache, CultCacheRegistry};
|
||||||
|
|
||||||
/// Registers the five kinds with a cache.
|
/// Registers the five kinds with a cache.
|
||||||
|
|
|
||||||
|
|
@ -1,12 +1,14 @@
|
||||||
//! Thing Script: the closed node union, the surface document that holds a tree of nodes, and the
|
//! Thing Script: the closed node union, the surface document that holds a tree of nodes, and the
|
||||||
//! composition document that names a reusable subtree. Arm keys are fixed for v1.
|
//! composition document that names a reusable subtree. Arm keys are fixed: Slot (13) is the arm
|
||||||
|
//! added after the first twelve, and a decoder from before it refuses a record holding one
|
||||||
|
//! (CultCache's unknown-arm rule).
|
||||||
|
|
||||||
use cultcache_rs::{CultSlots, CultUnion, DatabaseEntry};
|
use cultcache_rs::{CultSlots, CultUnion, DatabaseEntry};
|
||||||
|
|
||||||
use crate::domain::{Count, Segment, Version};
|
use crate::domain::{Count, Segment, Version};
|
||||||
use crate::command::{CommandDecl, CommandRef};
|
use crate::command::{CommandDecl, CommandRef};
|
||||||
use crate::keys::{NodeId, ProviderId, composition_key, surface_key};
|
use crate::keys::{NodeId, ProviderId, composition_key, surface_key};
|
||||||
use crate::source::{Bind, BoolSource, CollectionSource, MemberPath, NumberSource, TextSource};
|
use crate::source::{Bind, BoolSource, CollectionSource, MemberPath, NumberSource, ParamName, TextSource};
|
||||||
use crate::style::{BoxStyle, Paint, Role};
|
use crate::style::{BoxStyle, Paint, Role};
|
||||||
|
|
||||||
/// What every node carries.
|
/// What every node carries.
|
||||||
|
|
@ -21,6 +23,7 @@ pub struct NodeCommon {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
||||||
|
#[cultcache(type_name = "GameCult.Thing.Contract.Node")]
|
||||||
pub enum Node {
|
pub enum Node {
|
||||||
#[cultcache(key = 0)]
|
#[cultcache(key = 0)]
|
||||||
Box(BoxNode),
|
Box(BoxNode),
|
||||||
|
|
@ -48,6 +51,8 @@ pub enum Node {
|
||||||
Embed(EmbedNode),
|
Embed(EmbedNode),
|
||||||
#[cultcache(key = 12)]
|
#[cultcache(key = 12)]
|
||||||
Use(UseNode),
|
Use(UseNode),
|
||||||
|
#[cultcache(key = 13)]
|
||||||
|
Slot(SlotNode),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||||
|
|
@ -159,8 +164,10 @@ pub struct TextInputNode {
|
||||||
pub common: NodeCommon,
|
pub common: NodeCommon,
|
||||||
#[cultcache(key = 1)]
|
#[cultcache(key = 1)]
|
||||||
pub multiline: bool,
|
pub multiline: bool,
|
||||||
|
/// Named `input_kind` in every runtime (Rust `input_kind`, C# `InputKind`, TypeScript `inputKind`): a field
|
||||||
|
/// named `kind` collides with the union tag in TypeScript. The wire is the slot key, 2.
|
||||||
#[cultcache(key = 2)]
|
#[cultcache(key = 2)]
|
||||||
pub kind: InputKind,
|
pub input_kind: InputKind,
|
||||||
#[cultcache(key = 3)]
|
#[cultcache(key = 3)]
|
||||||
pub placeholder: TextSource,
|
pub placeholder: TextSource,
|
||||||
#[cultcache(key = 4)]
|
#[cultcache(key = 4)]
|
||||||
|
|
@ -309,6 +316,13 @@ pub struct CompositionRef {
|
||||||
pub version: Version,
|
pub version: Version,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl CompositionRef {
|
||||||
|
/// The record key of the composition this names, from the one key function.
|
||||||
|
pub fn record_key(&self) -> String {
|
||||||
|
composition_key(&self.publisher, &self.name, self.version)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||||
pub struct UseNode {
|
pub struct UseNode {
|
||||||
#[cultcache(key = 0)]
|
#[cultcache(key = 0)]
|
||||||
|
|
@ -319,6 +333,15 @@ pub struct UseNode {
|
||||||
pub args: Vec<Arg>,
|
pub args: Vec<Arg>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Where a composition body places the nodes passed for its Slot parameter `param`. Only a child
|
||||||
|
/// list of a composition body holds one, and resolve refuses it elsewhere. It carries no
|
||||||
|
/// `NodeCommon`: the argument's nodes, keeping their caller-scope ids, replace it.
|
||||||
|
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||||
|
pub struct SlotNode {
|
||||||
|
#[cultcache(key = 0)]
|
||||||
|
pub param: ParamName,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||||
pub struct Arg {
|
pub struct Arg {
|
||||||
#[cultcache(key = 0)]
|
#[cultcache(key = 0)]
|
||||||
|
|
@ -422,7 +445,7 @@ pub struct SurfaceDocument {
|
||||||
pub title: String,
|
pub title: String,
|
||||||
#[cultcache(key = 4)]
|
#[cultcache(key = 4)]
|
||||||
pub root: Node,
|
pub root: Node,
|
||||||
#[cultcache(key = 5)]
|
#[cultcache(key = 5, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.CommandDecl>")]
|
||||||
pub commands: Vec<CommandDecl>,
|
pub commands: Vec<CommandDecl>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -442,7 +465,7 @@ pub struct CompositionDocument {
|
||||||
pub name: Segment,
|
pub name: Segment,
|
||||||
#[cultcache(key = 2)]
|
#[cultcache(key = 2)]
|
||||||
pub version: Version,
|
pub version: Version,
|
||||||
#[cultcache(key = 3)]
|
#[cultcache(key = 3, type_name = "System.Collections.Immutable.ImmutableArray<GameCult.Thing.Contract.ParamDecl>")]
|
||||||
pub params: Vec<ParamDecl>,
|
pub params: Vec<ParamDecl>,
|
||||||
#[cultcache(key = 4)]
|
#[cultcache(key = 4)]
|
||||||
pub body: Node,
|
pub body: Node,
|
||||||
|
|
|
||||||
|
|
@ -41,6 +41,7 @@ pub struct FailedOutcome {
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
#[derive(Clone, Debug, PartialEq, CultUnion)]
|
||||||
|
#[cultcache(type_name = "GameCult.Thing.Contract.Outcome")]
|
||||||
pub enum Outcome {
|
pub enum Outcome {
|
||||||
#[cultcache(key = 0)]
|
#[cultcache(key = 0)]
|
||||||
Pending(PendingOutcome),
|
Pending(PendingOutcome),
|
||||||
|
|
|
||||||
|
|
@ -81,7 +81,9 @@ pub enum StateSource {
|
||||||
Item,
|
Item,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A state record. An absent provider is the publisher of the document.
|
/// A state record. An absent provider is the publisher of the document. `schema` is the id the
|
||||||
|
/// provider's record type is registered under in its store: a provider's state type must have its
|
||||||
|
/// entry type equal to that schema id, because a store names a record's schema by its entry type.
|
||||||
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
#[derive(Clone, Debug, PartialEq, CultSlots)]
|
||||||
pub struct StateRef {
|
pub struct StateRef {
|
||||||
#[cultcache(key = 0)]
|
#[cultcache(key = 0)]
|
||||||
|
|
|
||||||
63
crates/thing-contract/tests/catalog_members.rs
Normal file
63
crates/thing-contract/tests/catalog_members.rs
Normal file
|
|
@ -0,0 +1,63 @@
|
||||||
|
//! The catalog rows the five document kinds publish are the rows the C# package declares:
|
||||||
|
//! `tests/thing-contract-parity/catalog-members.tsv`, which NameSetTests (C#) and parity.test.ts
|
||||||
|
//! (TypeScript) are held to as well. Schema ids differ by writer, so the comparison is by group,
|
||||||
|
//! as `catalogGroups` in parity.test.ts makes it.
|
||||||
|
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use cultcache_rs::{DatabaseEntry, SchemaCatalogMember, SingleFileMessagePackBackingStore};
|
||||||
|
use thing_contract::*;
|
||||||
|
|
||||||
|
fn tsv_groups() -> Vec<String> {
|
||||||
|
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/thing-contract-parity/catalog-members.tsv");
|
||||||
|
let text = std::fs::read_to_string(path).unwrap();
|
||||||
|
let mut groups: Vec<(String, Vec<String>)> = Vec::new();
|
||||||
|
for row in text.lines().filter(|line| !line.trim().is_empty()) {
|
||||||
|
let (schema, rest) = row.split_once('\t').unwrap();
|
||||||
|
match groups.iter_mut().find(|(id, _)| id == schema) {
|
||||||
|
Some((_, rows)) => rows.push(rest.to_string()),
|
||||||
|
None => groups.push((schema.to_string(), vec![rest.to_string()])),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sorted(groups.into_iter().map(|(_, rows)| rows.join("\n")).collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn group(members: &[SchemaCatalogMember]) -> String {
|
||||||
|
members.iter().map(|m| format!("{}\t{}\t{}", m.slot, m.member_name, m.type_name)).collect::<Vec<_>>().join("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sorted(mut groups: Vec<String>) -> Vec<String> {
|
||||||
|
groups.sort();
|
||||||
|
groups
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rows_equal_the_csharp_file() {
|
||||||
|
let mine = sorted(vec![
|
||||||
|
group(&SurfaceDocument::schema_members()),
|
||||||
|
group(&CompositionDocument::schema_members()),
|
||||||
|
group(&CommandInvocation::schema_members()),
|
||||||
|
group(&CommandResult::schema_members()),
|
||||||
|
group(&AssetCatalog::schema_members()),
|
||||||
|
]);
|
||||||
|
assert_eq!(mine, tsv_groups());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_committed_store_carries_the_rows() {
|
||||||
|
// Each runtime's committed store, this crate's own included, declares the C# catalog. The Rust
|
||||||
|
// reader does not compare member type names when it opens a store, so a drifted name in a
|
||||||
|
// store another runtime wrote fails here. A store is copied first: reading it creates a lock
|
||||||
|
// file beside it.
|
||||||
|
for file in ["written-by-rs.cc", "written-by-cs.cc", "written-by-ts.cc"] {
|
||||||
|
let committed = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/thing-contract-parity").join(file);
|
||||||
|
let work = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!("catalog-members-{file}"));
|
||||||
|
std::fs::create_dir_all(&work).unwrap();
|
||||||
|
let copy = work.join(file);
|
||||||
|
std::fs::copy(committed, ©).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);
|
||||||
|
}
|
||||||
|
}
|
||||||
63
crates/thing-contract/tests/foreign_stores.rs
Normal file
63
crates/thing-contract/tests/foreign_stores.rs
Normal file
|
|
@ -0,0 +1,63 @@
|
||||||
|
//! The stores the other two runtimes wrote. `written-by-cs.cc` and `written-by-ts.cc` in
|
||||||
|
//! `tests/thing-contract-parity` are read here, never written: each opens to exactly the five
|
||||||
|
//! records, each re-encodes to its value golden, and each sits under the key the other runtimes
|
||||||
|
//! key it by. The file is copied first: reading a store creates a lock file beside it.
|
||||||
|
|
||||||
|
use std::fmt::Debug;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use cultcache_rs::DatabaseEntry;
|
||||||
|
use thing_contract::*;
|
||||||
|
use thing_testkit::{golden, store};
|
||||||
|
|
||||||
|
fn parity_dir() -> PathBuf {
|
||||||
|
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/thing-contract-parity")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn goldens_dir() -> PathBuf {
|
||||||
|
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scratch(purpose: &str, bytes: &[u8]) -> PathBuf {
|
||||||
|
static SERIAL: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
|
||||||
|
let serial = SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
|
||||||
|
let work = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join(format!("foreign-{purpose}-{serial}"));
|
||||||
|
std::fs::create_dir_all(&work).unwrap();
|
||||||
|
let copy = work.join("store.cc");
|
||||||
|
std::fs::write(©, 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");
|
||||||
|
}
|
||||||
|
|
@ -2,42 +2,29 @@
|
||||||
//! byte. The TypeScript and C# packages and core are held to these files; none of them writes
|
//! byte. The TypeScript and C# packages and core are held to these files; none of them writes
|
||||||
//! one. `THING_BLESS=1` rewrites them; any other run compares.
|
//! one. `THING_BLESS=1` rewrites them; any other run compares.
|
||||||
|
|
||||||
mod common;
|
|
||||||
|
|
||||||
use std::collections::BTreeSet;
|
use std::collections::BTreeSet;
|
||||||
use std::fmt::Debug;
|
use std::fmt::Debug;
|
||||||
use std::path::PathBuf;
|
use std::path::PathBuf;
|
||||||
|
|
||||||
use common::*;
|
use thing_testkit::{build::*, golden, store};
|
||||||
use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry, SingleFileMessagePackBackingStore};
|
use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry};
|
||||||
use thing_contract::*;
|
use thing_contract::*;
|
||||||
|
|
||||||
const PINNED_CLOCK: &str = "2026-01-01T00:00:00Z";
|
|
||||||
// A value that must never appear in a refusal.
|
|
||||||
const CANARY: &str = "CANARY-7f3a91c2";
|
|
||||||
|
|
||||||
fn goldens_dir() -> PathBuf {
|
fn goldens_dir() -> PathBuf {
|
||||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
|
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
|
||||||
}
|
}
|
||||||
|
|
||||||
fn blessing() -> bool {
|
/// Where the stores of all three runtimes live; this crate writes `written-by-rs.cc` there.
|
||||||
std::env::var("THING_BLESS").as_deref() == Ok("1")
|
fn parity_dir() -> PathBuf {
|
||||||
|
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../tests/thing-contract-parity")
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Bless the file or compare against it. Returns the committed bytes.
|
// A value that must never appear in a refusal.
|
||||||
fn golden_bytes(file: &str, produced: &[u8]) -> Vec<u8> {
|
const CANARY: &str = "CANARY-7f3a91c2";
|
||||||
let path = goldens_dir().join(file);
|
|
||||||
if blessing() {
|
|
||||||
std::fs::write(&path, produced).unwrap_or_else(|error| panic!("{file}: {error}"));
|
|
||||||
}
|
|
||||||
let committed = std::fs::read(&path).unwrap_or_else(|error| panic!("{file}: {error}"));
|
|
||||||
assert_eq!(committed, produced, "{file}: the committed golden differs from what the crate writes");
|
|
||||||
committed
|
|
||||||
}
|
|
||||||
|
|
||||||
fn golden<T: DatabaseEntry + PartialEq + Debug>(name: &str, value: &T) -> String {
|
fn golden<T: DatabaseEntry + PartialEq + Debug>(name: &str, value: &T) -> String {
|
||||||
let produced = rmp_serde::to_vec(value).unwrap();
|
let produced = rmp_serde::to_vec(value).unwrap();
|
||||||
let committed = golden_bytes(&format!("{name}.bin"), &produced);
|
let committed = golden::check(&goldens_dir(), &format!("{name}.bin"), &produced);
|
||||||
let decoded: T = rmp_serde::from_slice(&committed).unwrap_or_else(|error| panic!("{name}: {error}"));
|
let decoded: T = rmp_serde::from_slice(&committed).unwrap_or_else(|error| panic!("{name}: {error}"));
|
||||||
assert_eq!(&decoded, value, "{name}: the golden does not decode to the constructed value");
|
assert_eq!(&decoded, value, "{name}: the golden does not decode to the constructed value");
|
||||||
assert_eq!(rmp_serde::to_vec(&decoded).unwrap(), committed, "{name}: re-encoding changed the bytes");
|
assert_eq!(rmp_serde::to_vec(&decoded).unwrap(), committed, "{name}: re-encoding changed the bytes");
|
||||||
|
|
@ -150,7 +137,7 @@ fn full_surface() -> SurfaceDocument {
|
||||||
Node::TextInput(TextInputNode {
|
Node::TextInput(TextInputNode {
|
||||||
common: common("name-input"),
|
common: common("name-input"),
|
||||||
multiline: true,
|
multiline: true,
|
||||||
kind: InputKind::Number,
|
input_kind: InputKind::Number,
|
||||||
placeholder: lit_text("name"),
|
placeholder: lit_text("name"),
|
||||||
initial: TextSource::Param(param("initial")),
|
initial: TextSource::Param(param("initial")),
|
||||||
submit: command("rename"),
|
submit: command("rename"),
|
||||||
|
|
@ -158,7 +145,7 @@ fn full_surface() -> SurfaceDocument {
|
||||||
Node::TextInput(TextInputNode {
|
Node::TextInput(TextInputNode {
|
||||||
common: common("title-input"),
|
common: common("title-input"),
|
||||||
multiline: false,
|
multiline: false,
|
||||||
kind: InputKind::Text,
|
input_kind: InputKind::Text,
|
||||||
placeholder: lit_text("title"),
|
placeholder: lit_text("title"),
|
||||||
initial: TextSource::Param(param("initial")),
|
initial: TextSource::Param(param("initial")),
|
||||||
submit: command("retitle"),
|
submit: command("retitle"),
|
||||||
|
|
@ -384,7 +371,10 @@ fn full_composition() -> CompositionDocument {
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.map(|(name, kind)| ParamDecl { name: name.into(), kind })
|
.map(|(name, kind)| ParamDecl { name: name.into(), kind })
|
||||||
.collect(),
|
.collect(),
|
||||||
body: boxed("panel-root", vec![text("panel-title", "t"), inner_use]),
|
body: boxed(
|
||||||
|
"panel-root",
|
||||||
|
vec![text("panel-title", "t"), inner_use, Node::Slot(SlotNode { param: param("body") })],
|
||||||
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -435,26 +425,17 @@ fn asset_catalog() -> AssetCatalog {
|
||||||
|
|
||||||
/// A store with one record of each kind, written by cultcache-rs under a pinned clock.
|
/// A store with one record of each kind, written by cultcache-rs under a pinned clock.
|
||||||
fn write_store(path: &std::path::Path) {
|
fn write_store(path: &std::path::Path) {
|
||||||
let _ = std::fs::remove_file(path);
|
let mut cache = store::create(path);
|
||||||
let mut cache = CultCache::new();
|
|
||||||
ThingContract.register_entries(&mut cache).unwrap();
|
|
||||||
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap();
|
|
||||||
let surface = full_surface();
|
let surface = full_surface();
|
||||||
let composition = full_composition();
|
let composition = full_composition();
|
||||||
let invocation = invocation();
|
let invocation = invocation();
|
||||||
let result = CommandResult::pending(&invocation, seq(1), "working");
|
let result = CommandResult::pending(&invocation, seq(1), "working");
|
||||||
let catalog = asset_catalog();
|
let catalog = asset_catalog();
|
||||||
put(&mut cache, &surface.record_key(), &surface);
|
store::put_pinned(&mut cache, &surface.record_key(), &surface);
|
||||||
put(&mut cache, &composition.record_key(), &composition);
|
store::put_pinned(&mut cache, &composition.record_key(), &composition);
|
||||||
put(&mut cache, &invocation.record_key(), &invocation);
|
store::put_pinned(&mut cache, &invocation.record_key(), &invocation);
|
||||||
put(&mut cache, &result.record_key(), &result);
|
store::put_pinned(&mut cache, &result.record_key(), &result);
|
||||||
put(&mut cache, &catalog.record_key(), &catalog);
|
store::put_pinned(&mut cache, &catalog.record_key(), &catalog);
|
||||||
}
|
|
||||||
|
|
||||||
fn put<T: DatabaseEntry>(cache: &mut CultCache, key: &str, value: &T) {
|
|
||||||
let (mut envelope, _) = cache.prepare_entry(key, value).unwrap();
|
|
||||||
envelope.stored_at = PINNED_CLOCK.into();
|
|
||||||
cache.put_envelope::<T>(envelope).unwrap();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn envelope<T: DatabaseEntry>(key: &str, payload: Vec<u8>) -> CultCacheEnvelope {
|
fn envelope<T: DatabaseEntry>(key: &str, payload: Vec<u8>) -> CultCacheEnvelope {
|
||||||
|
|
@ -462,17 +443,17 @@ fn envelope<T: DatabaseEntry>(key: &str, payload: Vec<u8>) -> CultCacheEnvelope
|
||||||
key: key.into(),
|
key: key.into(),
|
||||||
r#type: T::TYPE.into(),
|
r#type: T::TYPE.into(),
|
||||||
payload,
|
payload,
|
||||||
stored_at: PINNED_CLOCK.into(),
|
stored_at: store::PINNED_CLOCK.into(),
|
||||||
schema_id: Some(T::TYPE.into()),
|
schema_id: Some(T::TYPE.into()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn open_store(path: &std::path::Path) -> CultCache {
|
#[test]
|
||||||
let mut cache = CultCache::new();
|
fn slot_arm_bytes() {
|
||||||
ThingContract.register_entries(&mut cache).unwrap();
|
let slot = Node::Slot(SlotNode { param: param("body") });
|
||||||
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(path)).unwrap();
|
let bytes = rmp_serde::to_vec(&slot).unwrap();
|
||||||
cache.pull_all_backing_stores().unwrap();
|
assert_eq!(bytes, [0x92, 0x0D, 0x91, 0x91, 0xA4, 0x62, 0x6F, 0x64, 0x79]);
|
||||||
cache
|
assert_eq!(rmp_serde::from_slice::<Node>(&bytes).unwrap(), slot);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|
@ -491,7 +472,7 @@ fn goldens_match() {
|
||||||
// that no case names is an orphan.
|
// that no case names is an orphan.
|
||||||
let refusals = refusal_payloads();
|
let refusals = refusal_payloads();
|
||||||
for (name, bytes) in &refusals {
|
for (name, bytes) in &refusals {
|
||||||
golden_bytes(&format!("{name}.bin"), bytes);
|
golden::check(&goldens_dir(), &format!("{name}.bin"), bytes);
|
||||||
names.insert((*name).to_string());
|
names.insert((*name).to_string());
|
||||||
}
|
}
|
||||||
let on_disk: BTreeSet<String> = std::fs::read_dir(goldens_dir())
|
let on_disk: BTreeSet<String> = std::fs::read_dir(goldens_dir())
|
||||||
|
|
@ -504,10 +485,11 @@ fn goldens_match() {
|
||||||
// The store: one record of each kind, written under a pinned clock, byte for byte.
|
// The store: one record of each kind, written under a pinned clock, byte for byte.
|
||||||
let scratch = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("goldens-surface.cc");
|
let scratch = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("goldens-surface.cc");
|
||||||
write_store(&scratch);
|
write_store(&scratch);
|
||||||
let committed = golden_bytes("surface.cc", &std::fs::read(&scratch).unwrap());
|
let parity = parity_dir();
|
||||||
let reopened = goldens_dir().join("surface.cc");
|
let committed = golden::check(&parity, "written-by-rs.cc", &std::fs::read(&scratch).unwrap());
|
||||||
|
let reopened = parity.join("written-by-rs.cc");
|
||||||
assert_eq!(std::fs::read(&reopened).unwrap(), committed);
|
assert_eq!(std::fs::read(&reopened).unwrap(), committed);
|
||||||
let cache = open_store(&scratch);
|
let cache = store::open(&scratch);
|
||||||
let surface = full_surface();
|
let surface = full_surface();
|
||||||
assert_eq!(cache.get::<SurfaceDocument>(&surface.record_key()).unwrap(), Some(surface));
|
assert_eq!(cache.get::<SurfaceDocument>(&surface.record_key()).unwrap(), Some(surface));
|
||||||
let composition = full_composition();
|
let composition = full_composition();
|
||||||
|
|
@ -553,10 +535,11 @@ fn refusal_payloads() -> Vec<(&'static str, Vec<u8>)> {
|
||||||
let root = text("root", "x");
|
let root = text("root", "x");
|
||||||
vec![
|
vec![
|
||||||
("result-thing1-flat", rmp_serde::to_vec_named(&flat).unwrap()),
|
("result-thing1-flat", rmp_serde::to_vec_named(&flat).unwrap()),
|
||||||
// A surface whose root is an arm key the Node union does not declare.
|
// A surface whose root is an arm key the Node union does not declare: 14 is the first key
|
||||||
|
// Node does not declare (Slot is 13).
|
||||||
(
|
(
|
||||||
"node-unknown-arm",
|
"node-unknown-arm",
|
||||||
rmp_serde::to_vec(&("provider.a", "main", 1i64, CANARY, (13i32, (CANARY,)), unit)).unwrap(),
|
rmp_serde::to_vec(&("provider.a", "main", 1i64, CANARY, (14i32, (CANARY,)), unit)).unwrap(),
|
||||||
),
|
),
|
||||||
// A result whose outcome is an arm key the Outcome union does not declare.
|
// A result whose outcome is an arm key the Outcome union does not declare.
|
||||||
("outcome-unknown-arm", rmp_serde::to_vec(&("inv-1", 1i32, (4i32, (CANARY,)))).unwrap()),
|
("outcome-unknown-arm", rmp_serde::to_vec(&("inv-1", 1i32, (4i32, (CANARY,)))).unwrap()),
|
||||||
|
|
@ -591,7 +574,7 @@ fn refusal_payloads() -> Vec<(&'static str, Vec<u8>)> {
|
||||||
#[test]
|
#[test]
|
||||||
fn refusal_cases() {
|
fn refusal_cases() {
|
||||||
let payloads: std::collections::BTreeMap<_, _> = refusal_payloads().into_iter().collect();
|
let payloads: std::collections::BTreeMap<_, _> = refusal_payloads().into_iter().collect();
|
||||||
let committed = |name: &str| golden_bytes(&format!("{name}.bin"), &payloads[name]);
|
let committed = |name: &str| golden::check(&goldens_dir(), &format!("{name}.bin"), &payloads[name]);
|
||||||
|
|
||||||
// Stored under their key, each is refused naming the kind and the key, never a value.
|
// Stored under their key, each is refused naming the kind and the key, never a value.
|
||||||
let cases: [(&str, &str, &str); 7] = [
|
let cases: [(&str, &str, &str); 7] = [
|
||||||
|
|
@ -623,7 +606,7 @@ fn refusal_cases() {
|
||||||
}
|
}
|
||||||
|
|
||||||
// Decoded directly, the refusal names the union and the arm key, and never the payload.
|
// Decoded directly, the refusal names the union and the arm key, and never the payload.
|
||||||
for (name, union, key) in [("node-unknown-arm", "Node", "13"), ("outcome-unknown-arm", "Outcome", "4")] {
|
for (name, union, key) in [("node-unknown-arm", "Node", "14"), ("outcome-unknown-arm", "Outcome", "4")] {
|
||||||
let bytes = committed(name);
|
let bytes = committed(name);
|
||||||
let message = if union == "Node" {
|
let message = if union == "Node" {
|
||||||
rmp_serde::from_slice::<SurfaceDocument>(&bytes).unwrap_err().to_string()
|
rmp_serde::from_slice::<SurfaceDocument>(&bytes).unwrap_err().to_string()
|
||||||
|
|
@ -665,13 +648,6 @@ fn refusal_cases() {
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn deep_tree() {
|
fn deep_tree() {
|
||||||
// Decoding a Node costs tens of KiB of debug stack per nesting level, so the chain runs on a
|
|
||||||
// thread that has the room; the 2 MiB default does not. The hazard is CultCache's, owned by
|
|
||||||
// cultlib-gaps:follow_up:decode-stack-safety; the test stays on the big thread until it lands.
|
|
||||||
std::thread::Builder::new().stack_size(16 * 1024 * 1024).spawn(deep_tree_body).unwrap().join().unwrap();
|
|
||||||
}
|
|
||||||
|
|
||||||
fn deep_tree_body() {
|
|
||||||
// A 64-deep Box chain.
|
// A 64-deep Box chain.
|
||||||
let mut chain = text("leaf", "bottom");
|
let mut chain = text("leaf", "bottom");
|
||||||
for depth in (0..64).rev() {
|
for depth in (0..64).rev() {
|
||||||
|
|
@ -698,15 +674,12 @@ fn deep_tree_body() {
|
||||||
};
|
};
|
||||||
|
|
||||||
let path = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("deep-tree.cc");
|
let path = PathBuf::from(env!("CARGO_TARGET_TMPDIR")).join("deep-tree.cc");
|
||||||
let _ = std::fs::remove_file(&path);
|
|
||||||
{
|
{
|
||||||
let mut cache = CultCache::new();
|
let mut cache = store::create(&path);
|
||||||
ThingContract.register_entries(&mut cache).unwrap();
|
store::put_pinned(&mut cache, &deep.record_key(), &deep);
|
||||||
cache.add_generic_backing_store(SingleFileMessagePackBackingStore::new(&path)).unwrap();
|
store::put_pinned(&mut cache, &wide.record_key(), &wide);
|
||||||
put(&mut cache, &deep.record_key(), &deep);
|
|
||||||
put(&mut cache, &wide.record_key(), &wide);
|
|
||||||
}
|
}
|
||||||
let cache = open_store(&path);
|
let cache = store::open(&path);
|
||||||
assert_eq!(cache.get::<SurfaceDocument>(&deep.record_key()).unwrap(), Some(deep));
|
assert_eq!(cache.get::<SurfaceDocument>(&deep.record_key()).unwrap(), Some(deep));
|
||||||
assert_eq!(cache.get::<SurfaceDocument>(&wide.record_key()).unwrap(), Some(wide));
|
assert_eq!(cache.get::<SurfaceDocument>(&wide.record_key()).unwrap(), Some(wide));
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,42 +1,47 @@
|
||||||
# thing-contract goldens
|
# thing-contract goldens
|
||||||
|
|
||||||
Written only by `crates/thing-contract/tests/goldens.rs`, with `THING_BLESS=1` set on that test.
|
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
|
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.
|
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.
|
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
|
A union value is `[armKey, [armSlots...]]`; a unit arm is `[key, []]`. An optional member is nil
|
||||||
when absent. Arm keys are fixed for v1.
|
when absent. Arm keys are fixed for v1.
|
||||||
|
|
||||||
## Values (decode to the constructed value, re-encode to the same bytes)
|
## Values (decode to the constructed value, re-encode to the same bytes)
|
||||||
|
|
||||||
| File | Kind | Decodes to |
|
| File | Kind | Decodes to |
|
||||||
|---|---|---|
|
|---|---|---|
|
||||||
| `surface-all-arms.bin` | `gamecult.thing.surface.v1` | One surface with all 13 node arms (Box 0, Text 1, Image 2, Button 3, Toggle 4, Slider 5, TextInput 6 as both input kinds, Text 0 and Number 1, Select 7, Repeat 8, Overlay 9, Plot 10, Embed 11, Use 12), a Box chain four levels deep, every text, number and bool source arm, every Format arm, both state sources, both member steps, every dimension and colour arm, and two declared commands |
|
| `surface-all-arms.bin` | `gamecult.thing.surface.v1` | One surface with 13 of the 14 node arms (Box 0, Text 1, Image 2, Button 3, Toggle 4, Slider 5, TextInput 6 as both input kinds, Text 0 and Number 1, Select 7, Repeat 8, Overlay 9, Plot 10, Embed 11, Use 12; Slot 13 is in `composition-all-params`, a body being where a slot stands), a Box chain four levels deep, every text, number and bool source arm, every Format arm, both state sources, both member steps, every dimension and colour arm, and two declared commands |
|
||||||
| `composition-all-params.bin` | `gamecult.thing.composition.v1` | A composition with one parameter of each of the 7 kinds, whose body uses a composition with one argument of each of the 7 argument arms |
|
| `composition-all-params.bin` | `gamecult.thing.composition.v1` | A composition with one parameter of each of the 7 kinds, whose body uses a composition with one argument of each of the 7 argument arms and places the body slot (Slot 13) last in its root's children |
|
||||||
| `invocation-all-inputs.bin` | `gamecult.thing.command_invocation.v1` | An invocation with a payload record of bin bytes and one captured input of each of the 4 input arms |
|
| `invocation-all-inputs.bin` | `gamecult.thing.command_invocation.v1` | An invocation with a payload record of bin bytes and one captured input of each of the 4 input arms, source `go-button` and items `[outer, inner]` |
|
||||||
| `result-pending.bin` | `gamecult.thing.command_result.v1` | Outcome Pending, seq 1 |
|
| `result-pending.bin` | `gamecult.thing.command_result.v1` | Outcome Pending, seq 1 |
|
||||||
| `result-completed.bin` | same | Outcome Completed with source version 8, drafts cleared, no effect |
|
| `result-completed.bin` | same | Outcome Completed with source version 8, drafts cleared, no effect |
|
||||||
| `result-completed-open-surface.bin` | same | Completed with no source version and the OpenSurface effect |
|
| `result-completed-open-surface.bin` | same | Completed with no source version and the OpenSurface effect |
|
||||||
| `result-completed-open-external.bin` | same | Completed with the OpenExternal effect and a resume command |
|
| `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.bin` | same | Denied naming a node |
|
||||||
| `result-denied-no-node.bin` | same | Denied with a nil node |
|
| `result-denied-no-node.bin` | same | Denied with a nil node |
|
||||||
| `result-failed.bin` | same | Failed |
|
| `result-failed.bin` | same | Failed |
|
||||||
| `asset-catalog.bin` | `gamecult.thing.asset_catalog.v1` | Two assets |
|
| `asset-catalog.bin` | `gamecult.thing.asset_catalog.v1` | Two assets |
|
||||||
| `surface.cc` | single-file store | One record of each of the five kinds, written under the pinned clock `2026-01-01T00:00:00Z`; reading it and writing it again gives the same bytes |
|
|
||||||
|
## Refusals and tolerance
|
||||||
## Refusals and tolerance
|
|
||||||
|
| File | Payload | Expected |
|
||||||
| File | Payload | Expected |
|
|---|---|---|
|
||||||
|---|---|---|
|
| `result-thing1-flat.bin` | a MessagePack map with named members, the shape a Thing 1 provider wrote for a command result | refused when stored as a command result; the error names the kind and the record key and never a value |
|
||||||
| `result-thing1-flat.bin` | a MessagePack map with named members, the shape a Thing 1 provider wrote for a command result | refused when stored as a command result; the error names the kind and the record key and never a value |
|
| `node-unknown-arm.bin` | a surface whose root node has arm key 14, which Node does not declare | refused; the error names the kind and the record key, and decoded directly it names the union Node and the key 14, and never a value |
|
||||||
| `node-unknown-arm.bin` | a surface whose root node has arm key 13, which Node does not declare | refused; the error names the kind and the record key, and decoded directly it names the union Node and the key 13, and never a value |
|
| `outcome-unknown-arm.bin` | a result whose outcome has arm key 4, which Outcome does not declare | refused in the same way, naming the union Outcome and the key 4 |
|
||||||
| `outcome-unknown-arm.bin` | a result whose outcome has arm key 4, which Outcome does not declare | refused in the same way, naming the union Outcome and the key 4 |
|
| `result-extra-slot.bin` | a Pending result with a fourth slot past the last one declared | read: it decodes to the Pending result with seq 1 (CultLib's extra-trailing-slots ruling: read, never written back) |
|
||||||
| `result-extra-slot.bin` | a Pending result with a fourth slot past the last one declared | read: it decodes to the Pending result with seq 1 (CultLib's extra-trailing-slots ruling: read, never written back) |
|
| `result-seq-zero.bin` | a result whose seq slot is 0 | refused; the error names the kind and the record key, decoded directly it names Seq, and never a value |
|
||||||
| `result-seq-zero.bin` | a result whose seq slot is 0 | refused; the error names the kind and the record key, decoded directly it names Seq, and never a value |
|
| `surface-version-negative.bin` | a surface whose version slot is -1 | refused in the same way, naming Version |
|
||||||
| `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 |
|
||||||
| `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 |
|
||||||
| `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 |
|
||||||
| `rgba-channel-out-of-range.bin` | the Rgba slot array `[256, 0, 0, 255]` | refused when decoded as an Rgba: a channel is a byte, 0 to 255 |
|
|
||||||
|
Domain refusals are the contract's rule, which the TypeScript and C# packages mirror: each is held to refuse these files, without the leaf set a Rust `u8` or a checked newtype has.
|
||||||
Domain refusals are the contract's rule, which the TypeScript and C# packages mirror: each is held to refuse these files, without the leaf set a Rust `u8` or a checked newtype has.
|
|
||||||
|
## The nil vector
|
||||||
|
|
||||||
|
`nil-positions.tsv` is written only by `crates/thing-contract/tests/nil_positions.rs` (`THING_BLESS=1`). For every element inside an array, at every depth, of each value golden above (the eleven `.bin` files from `surface-all-arms` to `asset-catalog`), the test replaces that element with nil (`0xC0`) and decodes the whole payload with the Rust decode door, `rmp_serde::from_slice` into the golden's kind. A row is `golden`, `path` (dotted array indices from the root, e.g. `3.0.1`), the element's byte `start` and `end` in the golden, and `ACCEPT` or `REFUSE`. An accepted variant re-encodes to the spliced bytes. Maps are not walked.
|
||||||
|
|
||||||
|
A slot is required exactly when its Rust type is not optional, so `REFUSE` rows are the required slots and `ACCEPT` rows the optional ones. The Rust decode door decides every row; the TypeScript and C# packages keep no list of required slots and are held to every row.
|
||||||
|
|
|
||||||
Binary file not shown.
Binary file not shown.
2875
crates/thing-contract/tests/goldens/nil-positions.tsv
Normal file
2875
crates/thing-contract/tests/goldens/nil-positions.tsv
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -1 +1 @@
|
||||||
–ªprovider.a¤main¯CANARY-7f3a91c2’
‘¯CANARY-7f3a91c2<63>
|
–ªprovider.a¤main¯CANARY-7f3a91c2’‘¯CANARY-7f3a91c2<63>
|
||||||
Binary file not shown.
132
crates/thing-contract/tests/nil_positions.rs
Normal file
132
crates/thing-contract/tests/nil_positions.rs
Normal file
|
|
@ -0,0 +1,132 @@
|
||||||
|
//! The nil vector: for every element of every array of every value golden, the golden with that
|
||||||
|
//! element replaced by nil, and whether the Rust decode door accepts it. A slot is required
|
||||||
|
//! exactly when its Rust type is not optional, so the rows are the required-slot set; the C# and
|
||||||
|
//! TypeScript packages hold no list of their own and are held to every row.
|
||||||
|
//! `THING_BLESS=1` rewrites `goldens/nil-positions.tsv`; any other run compares.
|
||||||
|
|
||||||
|
use std::fmt::Debug;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use serde::Serialize;
|
||||||
|
use serde::de::DeserializeOwned;
|
||||||
|
use thing_contract::*;
|
||||||
|
use thing_testkit::golden;
|
||||||
|
|
||||||
|
/// One MessagePack value's byte span; `kids` is set for arrays only (maps are never walked).
|
||||||
|
struct Span {
|
||||||
|
start: usize,
|
||||||
|
end: usize,
|
||||||
|
kids: Option<Vec<Span>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn be(bytes: &[u8], at: usize, width: usize) -> usize {
|
||||||
|
bytes[at..at + width].iter().fold(0, |acc, byte| acc << 8 | *byte as usize)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn collection(bytes: &[u8], start: usize, mut at: usize, count: usize, is_array: bool) -> Span {
|
||||||
|
let mut kids = Vec::new();
|
||||||
|
for _ in 0..count {
|
||||||
|
let kid = item(bytes, at);
|
||||||
|
at = kid.end;
|
||||||
|
kids.push(kid);
|
||||||
|
}
|
||||||
|
Span { start, end: at, kids: is_array.then_some(kids) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn item(bytes: &[u8], at: usize) -> Span {
|
||||||
|
let tag = bytes[at];
|
||||||
|
let flat = |len: usize| Span { start: at, end: at + len, kids: None };
|
||||||
|
match tag {
|
||||||
|
0x00..=0x7f | 0xe0..=0xff | 0xc0 | 0xc2 | 0xc3 => flat(1),
|
||||||
|
0x80..=0x8f => collection(bytes, at, at + 1, (tag & 0x0f) as usize * 2, false),
|
||||||
|
0x90..=0x9f => collection(bytes, at, at + 1, (tag & 0x0f) as usize, true),
|
||||||
|
0xa0..=0xbf => flat(1 + (tag & 0x1f) as usize),
|
||||||
|
0xc4 | 0xd9 => flat(2 + be(bytes, at + 1, 1)),
|
||||||
|
0xc5 | 0xda => flat(3 + be(bytes, at + 1, 2)),
|
||||||
|
0xc6 | 0xdb => flat(5 + be(bytes, at + 1, 4)),
|
||||||
|
0xca => flat(5),
|
||||||
|
0xcb => flat(9),
|
||||||
|
0xcc | 0xd0 => flat(2),
|
||||||
|
0xcd | 0xd1 => flat(3),
|
||||||
|
0xce | 0xd2 => flat(5),
|
||||||
|
0xcf | 0xd3 => flat(9),
|
||||||
|
0xdc => collection(bytes, at, at + 3, be(bytes, at + 1, 2), true),
|
||||||
|
0xdd => collection(bytes, at, at + 5, be(bytes, at + 1, 4), true),
|
||||||
|
0xde => collection(bytes, at, at + 3, be(bytes, at + 1, 2) * 2, false),
|
||||||
|
0xdf => collection(bytes, at, at + 5, be(bytes, at + 1, 4) * 2, false),
|
||||||
|
0xd4 => flat(3),
|
||||||
|
0xd5 => flat(4),
|
||||||
|
0xd6 => flat(6),
|
||||||
|
0xd7 => flat(10),
|
||||||
|
0xd8 => flat(18),
|
||||||
|
0xc7 => flat(3 + be(bytes, at + 1, 1)),
|
||||||
|
0xc8 => flat(4 + be(bytes, at + 1, 2)),
|
||||||
|
0xc9 => flat(6 + be(bytes, at + 1, 4)),
|
||||||
|
_ => panic!("unsupported tag {tag:#x} at {at}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every element inside an array, at every depth, in walk order, with its dotted index path.
|
||||||
|
fn elements(span: &Span, prefix: &str, out: &mut Vec<(String, usize, usize)>) {
|
||||||
|
for (index, kid) in span.kids.iter().flatten().enumerate() {
|
||||||
|
let path = if prefix.is_empty() { index.to_string() } else { format!("{prefix}.{index}") };
|
||||||
|
out.push((path.clone(), kid.start, kid.end));
|
||||||
|
elements(kid, &path, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The rows of one golden: nil spliced over each element, decoded as `T`. An accepted variant
|
||||||
|
/// must re-encode to the spliced bytes.
|
||||||
|
fn rows<T: DeserializeOwned + Serialize + Debug>(file: &str, out: &mut String) -> (usize, usize) {
|
||||||
|
let bytes = golden::read(&goldens_dir(), &format!("{file}.bin"));
|
||||||
|
let mut found = Vec::new();
|
||||||
|
elements(&item(&bytes, 0), "", &mut found);
|
||||||
|
let (mut accepted, mut refused) = (0, 0);
|
||||||
|
for (path, start, end) in found {
|
||||||
|
let mut spliced = bytes[..start].to_vec();
|
||||||
|
spliced.push(0xc0);
|
||||||
|
spliced.extend_from_slice(&bytes[end..]);
|
||||||
|
let verdict = match rmp_serde::from_slice::<T>(&spliced) {
|
||||||
|
Ok(value) => {
|
||||||
|
assert_eq!(rmp_serde::to_vec(&value).unwrap(), spliced, "{file} {path}: an accepted nil must re-encode to the spliced bytes");
|
||||||
|
accepted += 1;
|
||||||
|
"ACCEPT"
|
||||||
|
}
|
||||||
|
Err(_) => {
|
||||||
|
refused += 1;
|
||||||
|
"REFUSE"
|
||||||
|
}
|
||||||
|
};
|
||||||
|
out.push_str(&format!("{file}\t{path}\t{start}\t{end}\t{verdict}\n"));
|
||||||
|
}
|
||||||
|
(accepted, refused)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn nil_positions_match() {
|
||||||
|
let mut table = String::new();
|
||||||
|
let mut totals = Vec::new();
|
||||||
|
totals.push(("surface-all-arms", rows::<SurfaceDocument>("surface-all-arms", &mut table)));
|
||||||
|
totals.push(("composition-all-params", rows::<CompositionDocument>("composition-all-params", &mut table)));
|
||||||
|
totals.push(("invocation-all-inputs", rows::<CommandInvocation>("invocation-all-inputs", &mut table)));
|
||||||
|
for file in [
|
||||||
|
"result-pending",
|
||||||
|
"result-completed",
|
||||||
|
"result-completed-open-surface",
|
||||||
|
"result-completed-open-external",
|
||||||
|
"result-denied",
|
||||||
|
"result-denied-no-node",
|
||||||
|
"result-failed",
|
||||||
|
] {
|
||||||
|
totals.push((file, rows::<CommandResult>(file, &mut table)));
|
||||||
|
}
|
||||||
|
totals.push(("asset-catalog", rows::<AssetCatalog>("asset-catalog", &mut table)));
|
||||||
|
for (file, (accepted, refused)) in &totals {
|
||||||
|
println!("NILTOTAL {file} accept={accepted} refuse={refused}");
|
||||||
|
}
|
||||||
|
golden::check(&goldens_dir(), "nil-positions.tsv", table.as_bytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
fn goldens_dir() -> PathBuf {
|
||||||
|
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
|
||||||
|
}
|
||||||
|
|
@ -1,6 +1,4 @@
|
||||||
mod common;
|
use thing_testkit::build::*;
|
||||||
|
|
||||||
use common::*;
|
|
||||||
use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry, decode_payload};
|
use cultcache_rs::{CultCache, CultCacheEnvelope, CultCacheRegistry, DatabaseEntry, decode_payload};
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use serde::de::IntoDeserializer;
|
use serde::de::IntoDeserializer;
|
||||||
|
|
|
||||||
20
crates/thing-core/Cargo.toml
Normal file
20
crates/thing-core/Cargo.toml
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
[package]
|
||||||
|
name = "thing-core"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
license = "MIT"
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
# Normal dependencies are thing-contract, stacker, taffy and the three Unicode tables of the Cells
|
||||||
|
# text engine (unicode-width, unicode-segmentation, unicode-linebreak): layout and terminal text
|
||||||
|
# are thing-core's job, and no Taffy type is in its public API.
|
||||||
|
[dependencies]
|
||||||
|
thing-contract = { path = "../thing-contract" }
|
||||||
|
stacker = "0.1.25"
|
||||||
|
taffy.workspace = true
|
||||||
|
unicode-width.workspace = true
|
||||||
|
unicode-segmentation.workspace = true
|
||||||
|
unicode-linebreak.workspace = true
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
thing-testkit = { path = "../thing-testkit" }
|
||||||
172
crates/thing-core/src/bind/format.rs
Normal file
172
crates/thing-core/src/bind/format.rs
Normal file
|
|
@ -0,0 +1,172 @@
|
||||||
|
//! Format: total and locale-free. Each function takes the value the site read and returns the
|
||||||
|
//! text, or the reason the value does not fit (a detail that never carries the value).
|
||||||
|
|
||||||
|
use thing_contract::{AffixFormat, NumberFormat, is_timestamp_text};
|
||||||
|
|
||||||
|
/// Fixed-point text of `n` at `format.precision`, scaled by 100 for a percent, with the percent
|
||||||
|
/// sign and the unit. Non-finite numbers print as NaN, inf, -inf; negative zero prints as zero.
|
||||||
|
pub fn number(n: f64, format: &NumberFormat) -> String {
|
||||||
|
let scaled = if format.percent { n * 100.0 } else { n };
|
||||||
|
let mut text = if scaled.is_nan() {
|
||||||
|
"NaN".to_string()
|
||||||
|
} else if scaled.is_infinite() {
|
||||||
|
if scaled > 0.0 { "inf" } else { "-inf" }.to_string()
|
||||||
|
} else {
|
||||||
|
format!("{scaled:.*}", format.precision.get() as usize)
|
||||||
|
};
|
||||||
|
if text.starts_with('-') && text[1..].bytes().all(|byte| byte == b'0' || byte == b'.') {
|
||||||
|
text.remove(0);
|
||||||
|
}
|
||||||
|
if format.percent {
|
||||||
|
text.push('%');
|
||||||
|
}
|
||||||
|
if let Some(unit) = &format.unit {
|
||||||
|
text.push(' ');
|
||||||
|
text.push_str(unit);
|
||||||
|
}
|
||||||
|
text
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Seconds rounded half away from zero, printed by the largest unit present with the later
|
||||||
|
/// units at two digits: `5s`, `1m 05s`, `1h 00m 05s`, `1d 01h 00m 00s`, a leading `-` when negative.
|
||||||
|
pub fn duration(seconds: f64) -> Result<String, &'static str> {
|
||||||
|
if !seconds.is_finite() {
|
||||||
|
return Err("a duration is not finite");
|
||||||
|
}
|
||||||
|
let total = seconds.round() as i128;
|
||||||
|
let t = total.unsigned_abs();
|
||||||
|
let (days, hours, minutes, secs) = (t / 86_400, t % 86_400 / 3_600, t % 3_600 / 60, t % 60);
|
||||||
|
let body = if days > 0 {
|
||||||
|
format!("{days}d {hours:02}h {minutes:02}m {secs:02}s")
|
||||||
|
} else if hours > 0 {
|
||||||
|
format!("{hours}h {minutes:02}m {secs:02}s")
|
||||||
|
} else if minutes > 0 {
|
||||||
|
format!("{minutes}m {secs:02}s")
|
||||||
|
} else {
|
||||||
|
format!("{secs}s")
|
||||||
|
};
|
||||||
|
Ok(if total < 0 { format!("-{body}") } else { body })
|
||||||
|
}
|
||||||
|
|
||||||
|
const FIRST_SECOND: i128 = -62_135_596_800; // 0001-01-01T00:00:00Z
|
||||||
|
const LAST_SECOND: i128 = 253_402_300_799; // 9999-12-31T23:59:59Z
|
||||||
|
|
||||||
|
/// Unix seconds, floored, as `YYYY-MM-DDTHH:MM:SSZ` in UTC, years 0001 to 9999.
|
||||||
|
pub fn timestamp(seconds: f64) -> Result<String, &'static str> {
|
||||||
|
if !seconds.is_finite() {
|
||||||
|
return Err("a timestamp is not finite");
|
||||||
|
}
|
||||||
|
let floored = seconds.floor() as i128;
|
||||||
|
if !(FIRST_SECOND..=LAST_SECOND).contains(&floored) {
|
||||||
|
return Err("a timestamp is outside years 0001 to 9999");
|
||||||
|
}
|
||||||
|
let (days, rest) = (floored.div_euclid(86_400), floored.rem_euclid(86_400));
|
||||||
|
let (year, month, day) = civil(days as i64);
|
||||||
|
Ok(format!("{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z", rest / 3_600, rest % 3_600 / 60, rest % 60))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Days since 1970-01-01 as a proleptic Gregorian date.
|
||||||
|
fn civil(days: i64) -> (i64, i64, i64) {
|
||||||
|
let z = days + 719_468;
|
||||||
|
let era = z.div_euclid(146_097);
|
||||||
|
let day_of_era = z.rem_euclid(146_097);
|
||||||
|
let year_of_era = (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
|
||||||
|
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
|
||||||
|
let month_index = (5 * day_of_year + 2) / 153;
|
||||||
|
let day = day_of_year - (153 * month_index + 2) / 5 + 1;
|
||||||
|
let month = if month_index < 10 { month_index + 3 } else { month_index - 9 };
|
||||||
|
(year_of_era + era * 400 + i64::from(month <= 2), month, day)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Text that is already a `stored_at` stamp, as written.
|
||||||
|
pub fn stamp(text: &str) -> Result<String, &'static str> {
|
||||||
|
if is_timestamp_text(text) { Ok(text.to_string()) } else { Err("the text is not a timestamp") }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn affix(text: &str, format: &AffixFormat) -> String {
|
||||||
|
format!("{}{text}{}", format.prefix, format.suffix)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use thing_contract::Count;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn fmt(precision: i32, percent: bool, unit: Option<&str>) -> NumberFormat {
|
||||||
|
NumberFormat { precision: Count::new(precision).unwrap(), percent, unit: unit.map(Into::into) }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn number_table() {
|
||||||
|
let table = [
|
||||||
|
(0.42, fmt(1, true, None), "42.0%"),
|
||||||
|
(3.14159, fmt(2, false, None), "3.14"),
|
||||||
|
(2.5, fmt(0, false, None), "2"),
|
||||||
|
(1234.5, fmt(1, false, Some("MB")), "1234.5 MB"),
|
||||||
|
(0.5, fmt(0, true, Some("of cap")), "50% of cap"),
|
||||||
|
(-0.0, fmt(1, false, None), "0.0"),
|
||||||
|
(-0.04, fmt(1, false, None), "0.0"),
|
||||||
|
(-1.25, fmt(1, false, None), "-1.2"),
|
||||||
|
(f64::NAN, fmt(2, true, None), "NaN%"),
|
||||||
|
(f64::INFINITY, fmt(2, false, Some("x")), "inf x"),
|
||||||
|
(f64::NEG_INFINITY, fmt(0, false, None), "-inf"),
|
||||||
|
];
|
||||||
|
for (n, format, expected) in table {
|
||||||
|
assert_eq!(number(n, &format), expected, "{n} {format:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn duration_table() {
|
||||||
|
let table = [
|
||||||
|
(0.0, "0s"),
|
||||||
|
(5.0, "5s"),
|
||||||
|
(59.4, "59s"),
|
||||||
|
(59.5, "1m 00s"),
|
||||||
|
(65.0, "1m 05s"),
|
||||||
|
(3605.0, "1h 00m 05s"),
|
||||||
|
(90_000.0, "1d 01h 00m 00s"),
|
||||||
|
(-65.0, "-1m 05s"),
|
||||||
|
(-0.4, "0s"),
|
||||||
|
(-0.5, "-1s"),
|
||||||
|
];
|
||||||
|
for (seconds, expected) in table {
|
||||||
|
assert_eq!(duration(seconds).unwrap(), expected, "{seconds}");
|
||||||
|
}
|
||||||
|
assert!(duration(f64::NAN).is_err() && duration(f64::INFINITY).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn timestamp_table() {
|
||||||
|
let table = [
|
||||||
|
(0.0, "1970-01-01T00:00:00Z"),
|
||||||
|
(0.9, "1970-01-01T00:00:00Z"),
|
||||||
|
(-0.1, "1969-12-31T23:59:59Z"),
|
||||||
|
(951_782_400.0, "2000-02-29T00:00:00Z"),
|
||||||
|
(1_767_225_600.0, "2026-01-01T00:00:00Z"),
|
||||||
|
(-62_135_596_800.0, "0001-01-01T00:00:00Z"),
|
||||||
|
(253_402_300_799.0, "9999-12-31T23:59:59Z"),
|
||||||
|
];
|
||||||
|
for (seconds, expected) in table {
|
||||||
|
assert_eq!(timestamp(seconds).unwrap(), expected, "{seconds}");
|
||||||
|
}
|
||||||
|
assert!(timestamp(253_402_300_800.0).is_err());
|
||||||
|
assert!(timestamp(-62_135_596_801.0).is_err());
|
||||||
|
assert!(timestamp(f64::NAN).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stamp_text_is_printed_as_written() {
|
||||||
|
assert_eq!(stamp("2026-01-01T00:00:00Z").unwrap(), "2026-01-01T00:00:00Z");
|
||||||
|
assert_eq!(stamp("2026-01-01T02:00:00.5+02:00").unwrap(), "2026-01-01T02:00:00.5+02:00");
|
||||||
|
assert!(stamp("yesterday").is_err());
|
||||||
|
assert!(stamp("2026-01-01 00:00:00Z").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn affix_wraps_text() {
|
||||||
|
let format = AffixFormat { prefix: "[".into(), suffix: "]".into() };
|
||||||
|
assert_eq!(affix("ok", &format), "[ok]");
|
||||||
|
}
|
||||||
|
}
|
||||||
368
crates/thing-core/src/bind/mod.rs
Normal file
368
crates/thing-core/src/bind/mod.rs
Normal file
|
|
@ -0,0 +1,368 @@
|
||||||
|
//! Bind: a `ResolvedTree` and provider state become a `BoundTree`, the value of every source
|
||||||
|
//! site of every node, the instances of every Repeat and the typed faults between. The Binder is
|
||||||
|
//! handed trees and the changes the frame owner drained; it never drains, never decodes and keeps
|
||||||
|
//! no state value beside the port: a changed address is read again. The state interests it holds
|
||||||
|
//! are exactly the ones the bound trees read, held through the shared `Ledger`.
|
||||||
|
//!
|
||||||
|
//! A bound tree is a side table over the resolved document, not a second node tree.
|
||||||
|
|
||||||
|
mod format;
|
||||||
|
mod repeat;
|
||||||
|
mod scope;
|
||||||
|
mod walk;
|
||||||
|
|
||||||
|
pub use scope::Located;
|
||||||
|
|
||||||
|
use std::collections::{BTreeMap, HashMap, HashSet};
|
||||||
|
|
||||||
|
use thing_contract::{AssetEntry, NodeId, SelectOption};
|
||||||
|
|
||||||
|
use crate::diagnostic::{Code, Diagnostic};
|
||||||
|
use crate::port::{Address, Change, Interest, Ledger, StatePort};
|
||||||
|
use crate::resolve::{Limits, ResolvedTree};
|
||||||
|
use walk::{Unit, Walker};
|
||||||
|
|
||||||
|
/// Every source site a node can carry. Closed.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||||
|
pub enum Field {
|
||||||
|
Visible,
|
||||||
|
A11yLabel,
|
||||||
|
Content,
|
||||||
|
Alt,
|
||||||
|
Enabled,
|
||||||
|
Checked,
|
||||||
|
Value,
|
||||||
|
Placeholder,
|
||||||
|
Initial,
|
||||||
|
Selected,
|
||||||
|
Options,
|
||||||
|
Series,
|
||||||
|
Asset,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Field {
|
||||||
|
pub fn name(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Field::Visible => "visible",
|
||||||
|
Field::A11yLabel => "a11y_label",
|
||||||
|
Field::Content => "content",
|
||||||
|
Field::Alt => "alt",
|
||||||
|
Field::Enabled => "enabled",
|
||||||
|
Field::Checked => "checked",
|
||||||
|
Field::Value => "value",
|
||||||
|
Field::Placeholder => "placeholder",
|
||||||
|
Field::Initial => "initial",
|
||||||
|
Field::Selected => "selected",
|
||||||
|
Field::Options => "options",
|
||||||
|
Field::Series => "series",
|
||||||
|
Field::Asset => "asset",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a site or a Repeat has no value. `detail` names the fault and never carries a state value.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct BindError {
|
||||||
|
pub code: Code,
|
||||||
|
pub detail: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What one site shows. A value is never coerced into another site type.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub enum Bound {
|
||||||
|
Text(String),
|
||||||
|
Number(f64),
|
||||||
|
Bool(bool),
|
||||||
|
Series(Vec<f64>),
|
||||||
|
Options(Vec<SelectOption>),
|
||||||
|
/// The catalog entry an Image names.
|
||||||
|
Asset(AssetEntry),
|
||||||
|
/// The record or the member is not there (or is nil).
|
||||||
|
Absent,
|
||||||
|
Error(BindError),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One instance of a Repeat's template: its key, and the template with derived ids, whose sites
|
||||||
|
/// are in the same table. A refused item's key is `!` and its record key.
|
||||||
|
///
|
||||||
|
/// The one id scheme is `scope_prefix`: an id inside an instance is its prefix followed by the
|
||||||
|
/// template's id, so a node in nested instances is the inner prefix, then the outer, then its declared id.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct Instance {
|
||||||
|
pub key: String,
|
||||||
|
/// What `Instance::scope_prefix` derived for this instance: each of the template's ids is this followed by the template id.
|
||||||
|
pub prefix: String,
|
||||||
|
pub root: thing_contract::Node,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The values of one resolved document.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct BoundTree {
|
||||||
|
tree: ResolvedTree,
|
||||||
|
values: HashMap<(NodeId, Field), Bound>,
|
||||||
|
instances: HashMap<NodeId, Vec<Instance>>,
|
||||||
|
repeat_errors: HashMap<NodeId, BindError>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BoundTree {
|
||||||
|
pub fn resolved(&self) -> &ResolvedTree {
|
||||||
|
&self.tree
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn value(&self, node: &NodeId, field: Field) -> Option<&Bound> {
|
||||||
|
self.values.get(&(node.clone(), field))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The instances of a Repeat, in collection order; none when the Repeat is in error.
|
||||||
|
pub fn instances(&self, repeat: &NodeId) -> &[Instance] {
|
||||||
|
self.instances.get(repeat).map_or(&[], Vec::as_slice)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a Repeat has no instances, when it is in error.
|
||||||
|
pub fn repeat_error(&self, repeat: &NodeId) -> Option<&BindError> {
|
||||||
|
self.repeat_errors.get(repeat)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every bound site, instances' included, sorted by node id and field.
|
||||||
|
pub fn sites(&self) -> Vec<(&NodeId, Field, &Bound)> {
|
||||||
|
let mut sites: Vec<_> = self.values.iter().map(|((node, field), bound)| (node, *field, bound)).collect();
|
||||||
|
sites.sort_by(|a, b| (a.0.as_str(), a.1).cmp(&(b.0.as_str(), b.1)));
|
||||||
|
sites
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What one bind or apply changed: per surface key, the node ids whose value changed (appeared,
|
||||||
|
/// vanished or differed) or whose Repeat instance set changed; and the diagnostics of sites that
|
||||||
|
/// entered an error or changed error code.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq)]
|
||||||
|
pub struct Applied {
|
||||||
|
pub dirty: BTreeMap<String, Vec<NodeId>>,
|
||||||
|
pub diagnostics: Vec<Diagnostic>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a surface's unit read and owns, so a unit can be replaced alone.
|
||||||
|
struct Owned {
|
||||||
|
values: Vec<(NodeId, Field)>,
|
||||||
|
repeats: Vec<NodeId>,
|
||||||
|
ids: Vec<NodeId>,
|
||||||
|
nodes: usize,
|
||||||
|
interests: HashSet<Interest>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Surface {
|
||||||
|
key: String,
|
||||||
|
bound: BoundTree,
|
||||||
|
tree_ids: HashSet<NodeId>,
|
||||||
|
parts: HashMap<Unit, Owned>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Binder {
|
||||||
|
limits: Limits,
|
||||||
|
surfaces: HashMap<String, Surface>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tree_ids(tree: &ResolvedTree) -> HashSet<NodeId> {
|
||||||
|
fn visit(node: &thing_contract::Node, out: &mut HashSet<NodeId>) {
|
||||||
|
crate::resolve::grow(|| {
|
||||||
|
out.extend(walk::common(node).map(|common| common.id.clone()));
|
||||||
|
if let thing_contract::Node::Repeat(repeat) = node {
|
||||||
|
visit(&repeat.template, out);
|
||||||
|
}
|
||||||
|
walk::children(node).iter().for_each(|child| visit(child, out));
|
||||||
|
})
|
||||||
|
}
|
||||||
|
let mut ids = HashSet::new();
|
||||||
|
visit(&tree.document().root, &mut ids);
|
||||||
|
ids
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Surface {
|
||||||
|
fn interests(&self) -> HashSet<Interest> {
|
||||||
|
self.parts.values().flat_map(|owned| owned.interests.iter().cloned()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bind the units `only` selects (all when `None`), replace what they owned, and report what
|
||||||
|
/// changed against what they held.
|
||||||
|
fn run(
|
||||||
|
&mut self,
|
||||||
|
limits: &Limits,
|
||||||
|
port: &mut dyn StatePort,
|
||||||
|
ledger: &mut Ledger,
|
||||||
|
only: Option<&HashSet<Unit>>,
|
||||||
|
) -> (Vec<NodeId>, Vec<Diagnostic>) {
|
||||||
|
let before = self.interests();
|
||||||
|
let mut old_values: HashMap<(NodeId, Field), Bound> = HashMap::new();
|
||||||
|
let mut old_keys: HashMap<NodeId, Vec<String>> = HashMap::new();
|
||||||
|
let mut old_errors: HashMap<NodeId, Code> = HashMap::new();
|
||||||
|
let retired: Vec<Unit> = match only {
|
||||||
|
None => self.parts.keys().cloned().collect(),
|
||||||
|
Some(only) => only.iter().filter(|unit| self.parts.contains_key(*unit)).cloned().collect(),
|
||||||
|
};
|
||||||
|
for unit in retired {
|
||||||
|
let Some(owned) = self.parts.remove(&unit) else { continue };
|
||||||
|
for key in owned.values {
|
||||||
|
if let Some(bound) = self.bound.values.remove(&key) {
|
||||||
|
old_values.insert(key, bound);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for repeat in owned.repeats {
|
||||||
|
if let Some(instances) = self.bound.instances.remove(&repeat) {
|
||||||
|
old_keys.insert(repeat.clone(), instances.into_iter().map(|instance| instance.key).collect());
|
||||||
|
}
|
||||||
|
if let Some(error) = self.bound.repeat_errors.remove(&repeat) {
|
||||||
|
old_errors.insert(repeat, error.code);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut taken = self.tree_ids.clone();
|
||||||
|
let mut spent = 0;
|
||||||
|
for owned in self.parts.values() {
|
||||||
|
taken.extend(owned.ids.iter().cloned());
|
||||||
|
spent += owned.nodes;
|
||||||
|
}
|
||||||
|
let provider = self.bound.tree.document().provider_id.clone();
|
||||||
|
let parts = Walker::new(&*port, &provider, limits, taken, limits.max_nodes.saturating_sub(spent), only)
|
||||||
|
.run(&self.bound.tree.document().root);
|
||||||
|
|
||||||
|
let mut diagnostics = Vec::new();
|
||||||
|
let mut dirty: Vec<NodeId> = Vec::new();
|
||||||
|
let mut note = |node: &NodeId, code: Code, detail: &str, was: Option<Code>| {
|
||||||
|
if was != Some(code) {
|
||||||
|
diagnostics.push(Diagnostic { code, surface: self.key.clone(), node: Some(node.clone()), detail: detail.to_string() });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
for (unit, part) in parts {
|
||||||
|
let mut owned = Owned {
|
||||||
|
values: Vec::new(),
|
||||||
|
repeats: Vec::new(),
|
||||||
|
ids: part.ids,
|
||||||
|
nodes: part.nodes,
|
||||||
|
interests: part.interests,
|
||||||
|
};
|
||||||
|
for (key, bound) in part.values {
|
||||||
|
let old = old_values.remove(&key);
|
||||||
|
if old.as_ref() != Some(&bound) {
|
||||||
|
dirty.push(key.0.clone());
|
||||||
|
}
|
||||||
|
if let Bound::Error(error) = &bound {
|
||||||
|
note(&key.0, error.code, &error.detail, match &old {
|
||||||
|
Some(Bound::Error(was)) => Some(was.code),
|
||||||
|
_ => None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
owned.values.push(key.clone());
|
||||||
|
self.bound.values.insert(key, bound);
|
||||||
|
}
|
||||||
|
for (repeat, error) in part.errors {
|
||||||
|
note(&repeat, error.code, &error.detail, old_errors.get(&repeat).copied());
|
||||||
|
self.bound.repeat_errors.insert(repeat, error);
|
||||||
|
}
|
||||||
|
for (repeat, instances) in part.instances {
|
||||||
|
let keys: Vec<String> = instances.iter().map(|instance| instance.key.clone()).collect();
|
||||||
|
if old_keys.remove(&repeat).as_ref() != Some(&keys) {
|
||||||
|
dirty.push(repeat.clone());
|
||||||
|
}
|
||||||
|
owned.repeats.push(repeat.clone());
|
||||||
|
self.bound.instances.insert(repeat, instances);
|
||||||
|
}
|
||||||
|
self.parts.insert(unit, owned);
|
||||||
|
}
|
||||||
|
// What the retired units held and the new ones no longer do has vanished.
|
||||||
|
dirty.extend(old_values.into_keys().map(|(node, _)| node));
|
||||||
|
dirty.extend(old_keys.into_keys());
|
||||||
|
|
||||||
|
ledger.diff(port, &before, &self.interests());
|
||||||
|
let mut seen = HashSet::new();
|
||||||
|
dirty.retain(|node| seen.insert(node.clone()));
|
||||||
|
dirty.sort_by(|a, b| a.as_str().cmp(b.as_str()));
|
||||||
|
(dirty, diagnostics)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn matching(&self, address: &Address) -> HashSet<Unit> {
|
||||||
|
self.parts
|
||||||
|
.iter()
|
||||||
|
.filter(|(_, owned)| owned.interests.iter().any(|interest| interest.matches(address)))
|
||||||
|
.map(|(unit, _)| unit.clone())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Binder {
|
||||||
|
pub fn new(limits: Limits) -> Self {
|
||||||
|
Self { limits, surfaces: HashMap::new() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bind a resolved tree. A tree for a surface already held replaces its tree: the walk, the
|
||||||
|
/// diff against what was bound and the interest diff are the same as an apply's.
|
||||||
|
pub fn bind(&mut self, tree: ResolvedTree, port: &mut dyn StatePort, ledger: &mut Ledger) -> Applied {
|
||||||
|
let key = tree.document().record_key();
|
||||||
|
let ids = tree_ids(&tree);
|
||||||
|
let surface = self.surfaces.entry(key.clone()).or_insert_with(|| Surface {
|
||||||
|
key: key.clone(),
|
||||||
|
bound: BoundTree {
|
||||||
|
tree: tree.clone(),
|
||||||
|
values: HashMap::new(),
|
||||||
|
instances: HashMap::new(),
|
||||||
|
repeat_errors: HashMap::new(),
|
||||||
|
},
|
||||||
|
tree_ids: HashSet::new(),
|
||||||
|
parts: HashMap::new(),
|
||||||
|
});
|
||||||
|
surface.bound.tree = tree;
|
||||||
|
surface.tree_ids = ids;
|
||||||
|
let (dirty, diagnostics) = surface.run(&self.limits, port, ledger, None);
|
||||||
|
Applied { dirty: BTreeMap::from([(key, dirty)]).into_iter().filter(|(_, ids)| !ids.is_empty()).collect(), diagnostics }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One drained change: nothing is read unless a held interest matches its address; then each
|
||||||
|
/// unit that read it is bound again from the port.
|
||||||
|
pub fn apply(&mut self, change: &Change, port: &mut dyn StatePort, ledger: &mut Ledger) -> Applied {
|
||||||
|
let address = match change {
|
||||||
|
Change::Upsert(entry) => &entry.address,
|
||||||
|
Change::Delete(address) => address,
|
||||||
|
Change::Refused(refusal) => &refusal.address,
|
||||||
|
};
|
||||||
|
let mut applied = Applied::default();
|
||||||
|
let mut keys: Vec<String> = self.surfaces.keys().cloned().collect();
|
||||||
|
keys.sort();
|
||||||
|
for key in keys {
|
||||||
|
let surface = self.surfaces.get_mut(&key).expect("key listed");
|
||||||
|
let units = surface.matching(address);
|
||||||
|
if units.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let (dirty, diagnostics) = surface.run(&self.limits, port, ledger, Some(&units));
|
||||||
|
if !dirty.is_empty() {
|
||||||
|
applied.dirty.insert(key, dirty);
|
||||||
|
}
|
||||||
|
applied.diagnostics.extend(diagnostics);
|
||||||
|
}
|
||||||
|
applied
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drop a surface: its interests are released.
|
||||||
|
pub fn forget(&mut self, surface: &str, port: &mut dyn StatePort, ledger: &mut Ledger) {
|
||||||
|
if let Some(surface) = self.surfaces.remove(surface) {
|
||||||
|
ledger.diff(port, &surface.interests(), &HashSet::new());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn tree(&self, surface: &str) -> Option<&BoundTree> {
|
||||||
|
self.surfaces.get(surface).map(|surface| &surface.bound)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Instance {
|
||||||
|
/// The prefix of every id of the instance of `repeat` (a laid id) whose key is `key`:
|
||||||
|
/// `<repeat>#<key byte length>:<key>/`; an item the port refused has no key to read, so its
|
||||||
|
/// identity is its record key in the distinct form `<repeat>!<length>:<record key>/`. Resolve's
|
||||||
|
/// instance ids and command captures both derive scope here, so there is one scheme.
|
||||||
|
pub fn scope_prefix(repeat: &str, key: &str, refused: bool) -> String {
|
||||||
|
if refused {
|
||||||
|
format!("{repeat}!{}:{key}/", key.len())
|
||||||
|
} else {
|
||||||
|
format!("{repeat}#{}:{key}/", key.len())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
200
crates/thing-core/src/bind/repeat.rs
Normal file
200
crates/thing-core/src/bind/repeat.rs
Normal file
|
|
@ -0,0 +1,200 @@
|
||||||
|
//! Repeat: a collection's items become instances of the template, keyed so identity follows the
|
||||||
|
//! item. An instance's ids derive from (repeat id, key, template id) by one scheme:
|
||||||
|
//! `<repeat>#<key byte length>:<key>/<template id>`; an item the port refused has no key to read,
|
||||||
|
//! so its identity is its record key in the distinct form `<repeat>!<length>:<record key>/<template id>`.
|
||||||
|
//! A Repeat that cannot be instantiated is an error of that Repeat alone.
|
||||||
|
|
||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
|
use thing_contract::*;
|
||||||
|
|
||||||
|
use super::walk::{Item, Walker, children, common, fault, walk};
|
||||||
|
use super::{BindError, Instance};
|
||||||
|
use crate::diagnostic::Code;
|
||||||
|
use crate::port::{Lookup, Prefix, Record, StateValue};
|
||||||
|
use crate::resolve::grow;
|
||||||
|
|
||||||
|
/// One item of a collection. `record_key` is set for an item that is a record of its own.
|
||||||
|
pub(super) struct Entry {
|
||||||
|
pub record_key: Option<String>,
|
||||||
|
pub item: Item,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The key of an item: Text as it is, an Int in decimal.
|
||||||
|
fn key_of(value: &StateValue, path: &MemberPath) -> Result<String, BindError> {
|
||||||
|
match walk(value, path)? {
|
||||||
|
Some(StateValue::Text(text)) => Ok(text.clone()),
|
||||||
|
Some(StateValue::Int(n)) => Ok(n.to_string()),
|
||||||
|
Some(_) => Err(fault(Code::BindTypeMismatch, "an item key is not Text or Int")),
|
||||||
|
None => Err(fault(Code::BindTypeMismatch, "an item key is nil")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn collect_ids(node: &Node, out: &mut Vec<NodeId>) {
|
||||||
|
grow(|| {
|
||||||
|
out.extend(common(node).map(|common| common.id.clone()));
|
||||||
|
if let Node::Repeat(repeat) = node {
|
||||||
|
collect_ids(&repeat.template, out);
|
||||||
|
}
|
||||||
|
children(node).iter().for_each(|child| collect_ids(child, out));
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Give every id of the template, and every anchor that names one of them, the instance prefix.
|
||||||
|
fn rewrite(node: &mut Node, prefix: &str, inside: &HashSet<NodeId>) {
|
||||||
|
grow(|| {
|
||||||
|
let derive = |id: &mut NodeId| *id = NodeId::new(format!("{prefix}{}", id.as_str()));
|
||||||
|
match node {
|
||||||
|
Node::Box(n) => {
|
||||||
|
derive(&mut n.common.id);
|
||||||
|
n.children.iter_mut().for_each(|child| rewrite(child, prefix, inside));
|
||||||
|
}
|
||||||
|
Node::Button(n) => {
|
||||||
|
derive(&mut n.common.id);
|
||||||
|
n.content.iter_mut().for_each(|child| rewrite(child, prefix, inside));
|
||||||
|
}
|
||||||
|
Node::Overlay(n) => {
|
||||||
|
derive(&mut n.common.id);
|
||||||
|
if let Anchor::Node(anchor) = &mut n.anchor {
|
||||||
|
if inside.contains(&anchor.node) {
|
||||||
|
derive(&mut anchor.node);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
n.children.iter_mut().for_each(|child| rewrite(child, prefix, inside));
|
||||||
|
}
|
||||||
|
Node::Repeat(n) => {
|
||||||
|
derive(&mut n.common.id);
|
||||||
|
rewrite(&mut n.template, prefix, inside);
|
||||||
|
}
|
||||||
|
Node::Text(n) => derive(&mut n.common.id),
|
||||||
|
Node::Image(n) => derive(&mut n.common.id),
|
||||||
|
Node::Toggle(n) => derive(&mut n.common.id),
|
||||||
|
Node::Slider(n) => derive(&mut n.common.id),
|
||||||
|
Node::TextInput(n) => derive(&mut n.common.id),
|
||||||
|
Node::Select(n) => derive(&mut n.common.id),
|
||||||
|
Node::Plot(n) => derive(&mut n.common.id),
|
||||||
|
Node::Embed(n) => derive(&mut n.common.id),
|
||||||
|
Node::Use(n) => derive(&mut n.common.id),
|
||||||
|
Node::Slot(_) => {}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Walker<'_> {
|
||||||
|
/// The items of a collection, each a value or the fault that stands for it. Records read the
|
||||||
|
/// prefix, a Member reads the list of its holder; both leave their interest.
|
||||||
|
pub(super) fn collection(&mut self, source: &CollectionSource, item: Option<&Item>) -> Result<Vec<Entry>, BindError> {
|
||||||
|
match source {
|
||||||
|
CollectionSource::Records(records) => {
|
||||||
|
let provider = records.provider.clone().unwrap_or_else(|| self.provider.clone());
|
||||||
|
let prefix = Prefix { provider, schema: records.schema.clone(), key_prefix: records.key_prefix.clone() };
|
||||||
|
self.part.interests.insert(crate::port::Interest::Prefix(prefix.clone()));
|
||||||
|
Ok(self
|
||||||
|
.port
|
||||||
|
.list(&prefix)
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|lookup| match lookup {
|
||||||
|
Lookup::Present(entry) => {
|
||||||
|
let record_key = Some(entry.address.key.as_str().to_string());
|
||||||
|
Some(match entry.record {
|
||||||
|
Record::State { schema, value } if schema == records.schema => {
|
||||||
|
Entry { record_key, item: Item::Value(value) }
|
||||||
|
}
|
||||||
|
_ => Entry {
|
||||||
|
record_key,
|
||||||
|
item: Item::Fault(fault(
|
||||||
|
Code::BindSchemaMismatch,
|
||||||
|
format!("the record is not held under {}", records.schema.as_str()),
|
||||||
|
)),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
Lookup::Refused(refusal) => Some(Entry {
|
||||||
|
record_key: Some(refusal.address.key.as_str().to_string()),
|
||||||
|
item: Item::Fault(fault(Code::DecodeRefused, refusal.detail)),
|
||||||
|
}),
|
||||||
|
Lookup::Absent => None,
|
||||||
|
})
|
||||||
|
.collect())
|
||||||
|
}
|
||||||
|
CollectionSource::Member(bind) => self.with_source(&bind.source, item, |held| match held? {
|
||||||
|
None => Ok(Vec::new()),
|
||||||
|
Some(holder) => match walk(holder, &bind.member)? {
|
||||||
|
None => Ok(Vec::new()),
|
||||||
|
Some(StateValue::List(items)) => Ok(items
|
||||||
|
.iter()
|
||||||
|
.map(|value| Entry { record_key: None, item: Item::Value(value.clone()) })
|
||||||
|
.collect()),
|
||||||
|
Some(_) => Err(fault(Code::BindTypeMismatch, "a collection member is not a list")),
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
CollectionSource::Param(_) => {
|
||||||
|
Err(fault(Code::BindTypeMismatch, "a parameter that resolve left in the tree"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bind the instances of one Repeat, whole or not at all.
|
||||||
|
pub(super) fn repeat(&mut self, repeat: &RepeatNode, outer: Option<&Item>) {
|
||||||
|
let id = repeat.common.id.clone();
|
||||||
|
match self.instances(repeat, outer) {
|
||||||
|
Ok(instances) => self.part.instances.push((id, instances)),
|
||||||
|
Err(error) => {
|
||||||
|
self.part.errors.push((id.clone(), error));
|
||||||
|
self.part.instances.push((id, Vec::new()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn instances(&mut self, repeat: &RepeatNode, outer: Option<&Item>) -> Result<Vec<Instance>, BindError> {
|
||||||
|
let entries = self.collection(&repeat.collection, outer)?;
|
||||||
|
let id = repeat.common.id.as_str();
|
||||||
|
let mut template_ids = Vec::new();
|
||||||
|
collect_ids(&repeat.template, &mut template_ids);
|
||||||
|
let inside: HashSet<NodeId> = template_ids.into_iter().collect();
|
||||||
|
|
||||||
|
let mut keys = HashSet::new();
|
||||||
|
let mut built: Vec<(Instance, Item)> = Vec::with_capacity(entries.len());
|
||||||
|
for entry in entries {
|
||||||
|
let (key, prefix) = match &entry.item {
|
||||||
|
Item::Fault(_) => {
|
||||||
|
let record = entry.record_key.clone().unwrap_or_default();
|
||||||
|
let prefix = Instance::scope_prefix(id, &record, true);
|
||||||
|
(format!("!{record}"), prefix)
|
||||||
|
}
|
||||||
|
Item::Value(value) => {
|
||||||
|
let key = key_of(value, &repeat.key_member)?;
|
||||||
|
if !keys.insert(key.clone()) {
|
||||||
|
return Err(fault(Code::RepeatKeyDuplicate, format!("two items of {id} share one key")));
|
||||||
|
}
|
||||||
|
let prefix = Instance::scope_prefix(id, &key, false);
|
||||||
|
(key, prefix)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut root = (*repeat.template).clone();
|
||||||
|
rewrite(&mut root, &prefix, &inside);
|
||||||
|
built.push((Instance { key, prefix, root }, entry.item));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut ids = Vec::new();
|
||||||
|
for (instance, _) in &built {
|
||||||
|
collect_ids(&instance.root, &mut ids);
|
||||||
|
}
|
||||||
|
if ids.len() > self.budget.min(self.limits.max_nodes) {
|
||||||
|
return Err(fault(Code::ExpansionLimit, format!("the instances of {id} are past the node limit")));
|
||||||
|
}
|
||||||
|
let mut local = HashSet::new();
|
||||||
|
if ids.iter().any(|derived| self.taken.contains(derived) || !local.insert(derived)) {
|
||||||
|
return Err(fault(Code::DuplicateNodeId, format!("an instance id of {id} is already an id of the tree")));
|
||||||
|
}
|
||||||
|
|
||||||
|
self.budget -= ids.len();
|
||||||
|
self.part.nodes += ids.len();
|
||||||
|
self.taken.extend(ids.iter().cloned());
|
||||||
|
self.part.ids.extend(ids);
|
||||||
|
for (instance, item) in &built {
|
||||||
|
self.instance(&instance.root, item);
|
||||||
|
}
|
||||||
|
Ok(built.into_iter().map(|(instance, _)| instance).collect())
|
||||||
|
}
|
||||||
|
}
|
||||||
111
crates/thing-core/src/bind/scope.rs
Normal file
111
crates/thing-core/src/bind/scope.rs
Normal file
|
|
@ -0,0 +1,111 @@
|
||||||
|
//! Where a node sits in a bound tree: the one id -> node index, and the Repeat instances that
|
||||||
|
//! enclose a node, which commands read to name a row and to find the inputs beside a button.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use thing_contract::{Node, NodeId};
|
||||||
|
|
||||||
|
use super::walk::{children, common};
|
||||||
|
use super::BoundTree;
|
||||||
|
use crate::resolve::grow;
|
||||||
|
|
||||||
|
/// A node and the Repeat instances around it, read off the tree.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct Located<'a> {
|
||||||
|
pub node: &'a Node,
|
||||||
|
/// The id the author declared: the laid id with its instance prefixes removed.
|
||||||
|
pub declared: NodeId,
|
||||||
|
/// The prefix of each enclosing instance, innermost first. An id declared at the top of the
|
||||||
|
/// document, reached from here, is these joined in order followed by it.
|
||||||
|
pub prefixes: Vec<String>,
|
||||||
|
/// The key of each enclosing instance, outermost first.
|
||||||
|
pub items: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Walk<'a, 'b> {
|
||||||
|
tree: &'a BoundTree,
|
||||||
|
prefixes: Vec<&'a str>,
|
||||||
|
items: Vec<&'a str>,
|
||||||
|
visit: &'b mut dyn FnMut(Located<'a>) -> bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Walk<'a, '_> {
|
||||||
|
/// Visit the node, then what it holds; stops (`true`) as soon as a visit says so.
|
||||||
|
fn node(&mut self, node: &'a Node) -> bool {
|
||||||
|
grow(|| {
|
||||||
|
let Some(common) = common(node) else { return false };
|
||||||
|
let skip: usize = self.prefixes.iter().map(|prefix| prefix.len()).sum();
|
||||||
|
let declared = NodeId::new(common.id.as_str().get(skip..).unwrap_or(common.id.as_str()));
|
||||||
|
let located = Located {
|
||||||
|
node,
|
||||||
|
declared,
|
||||||
|
prefixes: self.prefixes.iter().rev().map(|prefix| prefix.to_string()).collect(),
|
||||||
|
items: self.items.iter().map(|item| item.to_string()).collect(),
|
||||||
|
};
|
||||||
|
if (self.visit)(located) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if let Node::Repeat(repeat) = node {
|
||||||
|
for instance in self.tree.instances(&repeat.common.id) {
|
||||||
|
self.prefixes.push(&instance.prefix);
|
||||||
|
self.items.push(&instance.key);
|
||||||
|
let stop = self.node(&instance.root);
|
||||||
|
self.prefixes.pop();
|
||||||
|
self.items.pop();
|
||||||
|
if stop {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
children(node).iter().any(|child| self.node(child))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BoundTree {
|
||||||
|
/// Every node of the document by laid id, Repeat instances included (ids are unique after
|
||||||
|
/// resolve). The one index render, hit-test and commands share.
|
||||||
|
pub fn index(&self) -> HashMap<&NodeId, &Node> {
|
||||||
|
let mut found = HashMap::new();
|
||||||
|
self.walk(&mut |located| {
|
||||||
|
if let Some(common) = common(located.node) {
|
||||||
|
found.insert(&common.id, located.node);
|
||||||
|
}
|
||||||
|
false
|
||||||
|
});
|
||||||
|
found
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The node with laid id `id`, and where it sits.
|
||||||
|
pub fn locate(&self, id: &NodeId) -> Option<Located<'_>> {
|
||||||
|
let mut found = None;
|
||||||
|
self.walk(&mut |located| {
|
||||||
|
let hit = common(located.node).is_some_and(|common| &common.id == id);
|
||||||
|
if hit {
|
||||||
|
found = Some(located);
|
||||||
|
}
|
||||||
|
hit
|
||||||
|
});
|
||||||
|
found
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first node declared as `declared` inside the instances keyed `items` (outermost first).
|
||||||
|
pub fn locate_source(&self, declared: &NodeId, items: &[String]) -> Option<Located<'_>> {
|
||||||
|
let mut found = None;
|
||||||
|
self.walk(&mut |located| {
|
||||||
|
let hit = &located.declared == declared && located.items == items;
|
||||||
|
if hit {
|
||||||
|
found = Some(located);
|
||||||
|
}
|
||||||
|
hit
|
||||||
|
});
|
||||||
|
found
|
||||||
|
}
|
||||||
|
|
||||||
|
fn walk<'a>(&'a self, visit: &mut dyn FnMut(Located<'a>) -> bool) {
|
||||||
|
let mut walk = Walk { tree: self, prefixes: Vec::new(), items: Vec::new(), visit };
|
||||||
|
walk.node(&self.resolved().document().root);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
402
crates/thing-core/src/bind/walk.rs
Normal file
402
crates/thing-core/src/bind/walk.rs
Normal file
|
|
@ -0,0 +1,402 @@
|
||||||
|
//! The walk: every source site of a node, read from the state port, a member path and a terminal
|
||||||
|
//! type. Nothing here keeps a value: the port is the truth.
|
||||||
|
|
||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
|
use thing_contract::*;
|
||||||
|
|
||||||
|
use super::format;
|
||||||
|
use super::{BindError, Bound, Field, Instance};
|
||||||
|
use crate::diagnostic::Code;
|
||||||
|
use crate::port::{Address, Entry, Interest, Lookup, Record, StatePort, StateValue};
|
||||||
|
use crate::resolve::{Limits, grow};
|
||||||
|
|
||||||
|
/// What a surface's values are re-evaluated by: one site, or one outermost Repeat (`None`).
|
||||||
|
pub(super) type Unit = (NodeId, Option<Field>);
|
||||||
|
|
||||||
|
/// What one unit bound: its values, its instance lists, its Repeat faults, the ids and node count
|
||||||
|
/// its instances take, and the interests it read.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub(super) struct Part {
|
||||||
|
pub values: Vec<((NodeId, Field), Bound)>,
|
||||||
|
pub instances: Vec<(NodeId, Vec<Instance>)>,
|
||||||
|
pub errors: Vec<(NodeId, BindError)>,
|
||||||
|
pub ids: Vec<NodeId>,
|
||||||
|
pub nodes: usize,
|
||||||
|
pub interests: HashSet<Interest>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The value a Repeat's template reads through `Item`.
|
||||||
|
pub(super) enum Item {
|
||||||
|
Value(StateValue),
|
||||||
|
Fault(BindError),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn fault(code: Code, detail: impl Into<String>) -> BindError {
|
||||||
|
BindError { code, detail: detail.into() }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub(super) enum Want {
|
||||||
|
Text,
|
||||||
|
Number,
|
||||||
|
Bool,
|
||||||
|
Series,
|
||||||
|
}
|
||||||
|
|
||||||
|
enum Site<'n> {
|
||||||
|
Bool(&'n BoolSource),
|
||||||
|
Text(&'n TextSource),
|
||||||
|
Number(&'n NumberSource),
|
||||||
|
Bind(&'n Bind, Want),
|
||||||
|
Options(&'n OptionList),
|
||||||
|
Asset(&'n ImageNode),
|
||||||
|
}
|
||||||
|
|
||||||
|
fn kind(value: &StateValue) -> &'static str {
|
||||||
|
match value {
|
||||||
|
StateValue::Nil => "nil",
|
||||||
|
StateValue::Bool(_) => "bool",
|
||||||
|
StateValue::Int(_) => "int",
|
||||||
|
StateValue::Float(_) => "float",
|
||||||
|
StateValue::Text(_) => "text",
|
||||||
|
StateValue::Bytes(_) => "bytes",
|
||||||
|
StateValue::List(_) => "list",
|
||||||
|
StateValue::Record(_) => "record",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn number_of(value: &StateValue) -> Option<f64> {
|
||||||
|
match value {
|
||||||
|
StateValue::Int(n) => Some(*n as f64),
|
||||||
|
StateValue::Float(n) => Some(*n),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Walk `path` from `value`. `Ok(None)` is a Nil reached, which is absence.
|
||||||
|
pub(super) fn walk<'v>(mut value: &'v StateValue, path: &MemberPath) -> Result<Option<&'v StateValue>, BindError> {
|
||||||
|
for step in &path.steps {
|
||||||
|
if matches!(value, StateValue::Nil) {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
value = match (step, value) {
|
||||||
|
(MemberStep::Name(step), StateValue::Record(_)) => value
|
||||||
|
.member(&step.name)
|
||||||
|
.ok_or_else(|| fault(Code::BindMemberMissing, format!("the record has no member {}", step.name)))?,
|
||||||
|
(MemberStep::Index(step), StateValue::List(items)) => items.get(step.index.get() as usize).ok_or_else(|| {
|
||||||
|
fault(Code::BindMemberMissing, format!("the list has no index {}", step.index.get()))
|
||||||
|
})?,
|
||||||
|
(MemberStep::Name(step), other) => {
|
||||||
|
return Err(fault(Code::BindTypeMismatch, format!("member {} asked of a {}", step.name, kind(other))));
|
||||||
|
}
|
||||||
|
(MemberStep::Index(step), other) => {
|
||||||
|
return Err(fault(Code::BindTypeMismatch, format!("index {} asked of a {}", step.index.get(), kind(other))));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
Ok(if matches!(value, StateValue::Nil) { None } else { Some(value) })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A value at the type its site takes. No value is coerced; a Format is the only road from a
|
||||||
|
/// number to text.
|
||||||
|
fn terminal(value: &StateValue, want: Want, format: Option<&Format>) -> Result<Bound, BindError> {
|
||||||
|
let mismatch = |why: &str| Err(fault(Code::BindTypeMismatch, format!("{why}: a {} value", kind(value))));
|
||||||
|
if want != Want::Text && format.is_some() {
|
||||||
|
return mismatch("a Format on a site that is not text");
|
||||||
|
}
|
||||||
|
match want {
|
||||||
|
Want::Number => match number_of(value) {
|
||||||
|
Some(n) => Ok(Bound::Number(n)),
|
||||||
|
None => mismatch("a number site"),
|
||||||
|
},
|
||||||
|
Want::Bool => match value {
|
||||||
|
StateValue::Bool(b) => Ok(Bound::Bool(*b)),
|
||||||
|
_ => mismatch("a bool site"),
|
||||||
|
},
|
||||||
|
Want::Series => match value {
|
||||||
|
StateValue::List(items) => match items.iter().map(number_of).collect::<Option<Vec<f64>>>() {
|
||||||
|
Some(series) => Ok(Bound::Series(series)),
|
||||||
|
None => Err(fault(Code::BindTypeMismatch, "a series holds a member that is not a number")),
|
||||||
|
},
|
||||||
|
_ => mismatch("a series site"),
|
||||||
|
},
|
||||||
|
Want::Text => {
|
||||||
|
let text = match (value, format) {
|
||||||
|
(StateValue::Text(text), None) => Ok(text.clone()),
|
||||||
|
(StateValue::Text(text), Some(Format::Affix(affix))) => Ok(format::affix(text, affix)),
|
||||||
|
(StateValue::Text(text), Some(Format::Timestamp)) => format::stamp(text),
|
||||||
|
(StateValue::Int(_) | StateValue::Float(_), Some(Format::Number(spec))) => {
|
||||||
|
Ok(format::number(number_of(value).unwrap(), spec))
|
||||||
|
}
|
||||||
|
(StateValue::Int(_) | StateValue::Float(_), Some(Format::Duration)) => {
|
||||||
|
format::duration(number_of(value).unwrap())
|
||||||
|
}
|
||||||
|
(StateValue::Int(_) | StateValue::Float(_), Some(Format::Timestamp)) => {
|
||||||
|
format::timestamp(number_of(value).unwrap())
|
||||||
|
}
|
||||||
|
_ => Err("the value does not fit the text site and its Format"),
|
||||||
|
};
|
||||||
|
text.map(Bound::Text).map_err(|why| fault(Code::BindTypeMismatch, format!("{why}: a {} value", kind(value))))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The Text at `path` of an item, for an option's value or label.
|
||||||
|
pub(super) fn item_text(value: &StateValue, path: &MemberPath) -> Result<String, BindError> {
|
||||||
|
match walk(value, path)? {
|
||||||
|
Some(StateValue::Text(text)) => Ok(text.clone()),
|
||||||
|
Some(other) => Err(fault(Code::BindTypeMismatch, format!("an option member is a {}", kind(other)))),
|
||||||
|
None => Err(fault(Code::BindTypeMismatch, "an option member is nil")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The sites of one node, in Field order.
|
||||||
|
fn sites(node: &Node) -> Vec<(Field, Site<'_>)> {
|
||||||
|
let mut found = Vec::new();
|
||||||
|
let Some(common) = common(node) else { return found };
|
||||||
|
found.push((Field::Visible, Site::Bool(&common.visible)));
|
||||||
|
if let Some(label) = &common.a11y_label {
|
||||||
|
found.push((Field::A11yLabel, Site::Text(label)));
|
||||||
|
}
|
||||||
|
match node {
|
||||||
|
Node::Text(n) => found.push((Field::Content, Site::Text(&n.content))),
|
||||||
|
Node::Image(n) => {
|
||||||
|
found.push((Field::Alt, Site::Text(&n.alt)));
|
||||||
|
found.push((Field::Asset, Site::Asset(n)));
|
||||||
|
}
|
||||||
|
Node::Button(n) => found.push((Field::Enabled, Site::Bool(&n.enabled))),
|
||||||
|
Node::Toggle(n) => found.push((Field::Checked, Site::Bool(&n.checked))),
|
||||||
|
Node::Slider(n) => found.push((Field::Value, Site::Number(&n.value))),
|
||||||
|
Node::TextInput(n) => {
|
||||||
|
found.push((Field::Placeholder, Site::Text(&n.placeholder)));
|
||||||
|
found.push((Field::Initial, Site::Text(&n.initial)));
|
||||||
|
}
|
||||||
|
Node::Select(n) => {
|
||||||
|
found.push((Field::Options, Site::Options(&n.options)));
|
||||||
|
found.push((Field::Selected, Site::Bind(&n.value, Want::Text)));
|
||||||
|
}
|
||||||
|
Node::Plot(n) => found.push((Field::Series, Site::Bind(&n.series, Want::Series))),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
found
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn common(node: &Node) -> Option<&NodeCommon> {
|
||||||
|
Some(match node {
|
||||||
|
Node::Box(n) => &n.common,
|
||||||
|
Node::Text(n) => &n.common,
|
||||||
|
Node::Image(n) => &n.common,
|
||||||
|
Node::Button(n) => &n.common,
|
||||||
|
Node::Toggle(n) => &n.common,
|
||||||
|
Node::Slider(n) => &n.common,
|
||||||
|
Node::TextInput(n) => &n.common,
|
||||||
|
Node::Select(n) => &n.common,
|
||||||
|
Node::Repeat(n) => &n.common,
|
||||||
|
Node::Overlay(n) => &n.common,
|
||||||
|
Node::Plot(n) => &n.common,
|
||||||
|
Node::Embed(n) => &n.common,
|
||||||
|
Node::Use(n) => &n.common,
|
||||||
|
Node::Slot(_) => return None,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The children a walk visits: a Repeat's template is instantiated, never visited as itself.
|
||||||
|
pub(super) fn children(node: &Node) -> &[Node] {
|
||||||
|
match node {
|
||||||
|
Node::Box(n) => &n.children,
|
||||||
|
Node::Button(n) => &n.content,
|
||||||
|
Node::Overlay(n) => &n.children,
|
||||||
|
_ => &[],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) struct Walker<'a> {
|
||||||
|
pub(super) port: &'a dyn StatePort,
|
||||||
|
pub(super) provider: &'a ProviderId,
|
||||||
|
pub(super) limits: &'a Limits,
|
||||||
|
/// Every id of the bound tree outside the units being walked, and the ones walked so far.
|
||||||
|
pub(super) taken: HashSet<NodeId>,
|
||||||
|
/// Instance nodes still allowed.
|
||||||
|
pub(super) budget: usize,
|
||||||
|
only: Option<&'a HashSet<Unit>>,
|
||||||
|
pub(super) part: Part,
|
||||||
|
done: Vec<(Unit, Part)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Walker<'a> {
|
||||||
|
pub(super) fn new(
|
||||||
|
port: &'a dyn StatePort,
|
||||||
|
provider: &'a ProviderId,
|
||||||
|
limits: &'a Limits,
|
||||||
|
taken: HashSet<NodeId>,
|
||||||
|
budget: usize,
|
||||||
|
only: Option<&'a HashSet<Unit>>,
|
||||||
|
) -> Self {
|
||||||
|
Self { port, provider, limits, taken, budget, only, part: Part::default(), done: Vec::new() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Walk the resolved root, binding every unit `only` selects (all when `None`).
|
||||||
|
pub(super) fn run(mut self, root: &Node) -> Vec<(Unit, Part)> {
|
||||||
|
self.top(root);
|
||||||
|
self.done
|
||||||
|
}
|
||||||
|
|
||||||
|
fn selects(&self, unit: &Unit) -> bool {
|
||||||
|
self.only.is_none_or(|only| only.contains(unit))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn end(&mut self, unit: Unit) {
|
||||||
|
let part = std::mem::take(&mut self.part);
|
||||||
|
self.done.push((unit, part));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn top(&mut self, node: &Node) {
|
||||||
|
grow(|| {
|
||||||
|
let Some(id) = common(node).map(|common| common.id.clone()) else { return };
|
||||||
|
for (field, site) in sites(node) {
|
||||||
|
let unit = (id.clone(), Some(field));
|
||||||
|
if self.selects(&unit) {
|
||||||
|
let value = self.eval(site, None);
|
||||||
|
self.part.values.push(((id.clone(), field), value));
|
||||||
|
self.end(unit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Node::Repeat(repeat) = node {
|
||||||
|
let unit = (id, None);
|
||||||
|
if self.selects(&unit) {
|
||||||
|
self.repeat(repeat, None);
|
||||||
|
self.end(unit);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
children(node).iter().for_each(|child| self.top(child));
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An instance's nodes: every site binds, with `item` as the Item.
|
||||||
|
pub(super) fn instance(&mut self, node: &Node, item: &Item) {
|
||||||
|
grow(|| {
|
||||||
|
let Some(id) = common(node).map(|common| common.id.clone()) else { return };
|
||||||
|
for (field, site) in sites(node) {
|
||||||
|
let value = self.eval(site, Some(item));
|
||||||
|
self.part.values.push(((id.clone(), field), value));
|
||||||
|
}
|
||||||
|
if let Node::Repeat(repeat) = node {
|
||||||
|
self.repeat(repeat, Some(item));
|
||||||
|
} else {
|
||||||
|
children(node).iter().for_each(|child| self.instance(child, item));
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn eval(&mut self, site: Site<'_>, item: Option<&Item>) -> Bound {
|
||||||
|
let unresolved = || Bound::Error(fault(Code::BindTypeMismatch, "a parameter that resolve left in the tree"));
|
||||||
|
match site {
|
||||||
|
Site::Bool(BoolSource::Literal(literal)) => Bound::Bool(literal.value),
|
||||||
|
Site::Bool(BoolSource::Bound(bind)) => self.bind(bind, Want::Bool, item),
|
||||||
|
Site::Text(TextSource::Literal(literal)) => Bound::Text(literal.value.clone()),
|
||||||
|
Site::Text(TextSource::Bound(bind)) => self.bind(bind, Want::Text, item),
|
||||||
|
Site::Number(NumberSource::Literal(literal)) => Bound::Number(literal.value),
|
||||||
|
Site::Number(NumberSource::Bound(bind)) => self.bind(bind, Want::Number, item),
|
||||||
|
Site::Bool(BoolSource::Param(_)) | Site::Text(TextSource::Param(_)) | Site::Number(NumberSource::Param(_)) => {
|
||||||
|
unresolved()
|
||||||
|
}
|
||||||
|
Site::Bind(bind, want) => self.bind(bind, want, item),
|
||||||
|
Site::Options(OptionList::Literal(literal)) => Bound::Options(literal.options.clone()),
|
||||||
|
Site::Options(OptionList::Bound(bound)) => self.options(bound, item),
|
||||||
|
Site::Asset(image) => self.asset(image),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hand `then` what `source` holds: a fault, absence, or the value. Records the interest a
|
||||||
|
/// Record source reads.
|
||||||
|
pub(super) fn with_source<R>(
|
||||||
|
&mut self,
|
||||||
|
source: &StateSource,
|
||||||
|
item: Option<&Item>,
|
||||||
|
then: impl FnOnce(Result<Option<&StateValue>, BindError>) -> R,
|
||||||
|
) -> R {
|
||||||
|
match source {
|
||||||
|
StateSource::Item => match item {
|
||||||
|
Some(Item::Value(value)) => then(Ok(Some(value))),
|
||||||
|
Some(Item::Fault(error)) => then(Err(error.clone())),
|
||||||
|
None => then(Err(fault(Code::BindTypeMismatch, "an Item source outside a Repeat"))),
|
||||||
|
},
|
||||||
|
StateSource::Record(reference) => {
|
||||||
|
let provider = reference.provider.clone().unwrap_or_else(|| self.provider.clone());
|
||||||
|
let address = Address { provider, schema: reference.schema.clone(), key: reference.key.clone() };
|
||||||
|
self.part.interests.insert(Interest::Record(address.clone()));
|
||||||
|
match self.port.read(&address) {
|
||||||
|
Lookup::Present(Entry { record: Record::State { schema, value }, .. }) if schema == reference.schema => {
|
||||||
|
then(Ok(Some(&value)))
|
||||||
|
}
|
||||||
|
Lookup::Present(_) => then(Err(fault(
|
||||||
|
Code::BindSchemaMismatch,
|
||||||
|
format!("the record is not held under {}", reference.schema.as_str()),
|
||||||
|
))),
|
||||||
|
Lookup::Absent => then(Ok(None)),
|
||||||
|
Lookup::Refused(refusal) => then(Err(fault(Code::DecodeRefused, refusal.detail))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bind(&mut self, bind: &Bind, want: Want, item: Option<&Item>) -> Bound {
|
||||||
|
self.with_source(&bind.source, item, |held| match held {
|
||||||
|
Err(error) => Bound::Error(error),
|
||||||
|
Ok(None) => Bound::Absent,
|
||||||
|
Ok(Some(value)) => match walk(value, &bind.member) {
|
||||||
|
Err(error) => Bound::Error(error),
|
||||||
|
Ok(None) => Bound::Absent,
|
||||||
|
Ok(Some(value)) => terminal(value, want, bind.format.as_ref()).unwrap_or_else(Bound::Error),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The catalog entry an Image names: the catalog record is one more interest of the Image.
|
||||||
|
fn asset(&mut self, image: &ImageNode) -> Bound {
|
||||||
|
let Ok(catalog) = Segment::new(image.catalog.as_str()) else {
|
||||||
|
return Bound::Error(fault(Code::AssetMissing, "catalog id is not one segment"));
|
||||||
|
};
|
||||||
|
let address = Address {
|
||||||
|
provider: self.provider.clone(),
|
||||||
|
schema: SchemaId::new(AssetCatalog::SCHEMA_NAME),
|
||||||
|
key: RecordKey::new(asset_catalog_key(self.provider, &catalog)),
|
||||||
|
};
|
||||||
|
self.part.interests.insert(Interest::Record(address.clone()));
|
||||||
|
match self.port.read(&address) {
|
||||||
|
Lookup::Present(Entry { record: Record::Catalog(held), .. }) => {
|
||||||
|
match held.assets.into_iter().find(|entry| entry.id == image.asset) {
|
||||||
|
Some(entry) => Bound::Asset(entry),
|
||||||
|
None => Bound::Error(fault(Code::AssetMissing, format!("no asset {} in the catalog", image.asset))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Lookup::Present(_) => Bound::Error(fault(
|
||||||
|
Code::BindSchemaMismatch,
|
||||||
|
format!("the record is not held under {}", AssetCatalog::SCHEMA_NAME),
|
||||||
|
)),
|
||||||
|
Lookup::Absent => Bound::Absent,
|
||||||
|
Lookup::Refused(refusal) => Bound::Error(fault(Code::DecodeRefused, refusal.detail)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn options(&mut self, bound: &BoundOptions, item: Option<&Item>) -> Bound {
|
||||||
|
let entries = match self.collection(&bound.collection, item) {
|
||||||
|
Ok(entries) => entries,
|
||||||
|
Err(error) => return Bound::Error(error),
|
||||||
|
};
|
||||||
|
let mut options = Vec::with_capacity(entries.len());
|
||||||
|
for entry in entries {
|
||||||
|
let value = match entry.item {
|
||||||
|
Item::Value(value) => value,
|
||||||
|
Item::Fault(error) => return Bound::Error(error),
|
||||||
|
};
|
||||||
|
match (item_text(&value, &bound.value_member), item_text(&value, &bound.label_member)) {
|
||||||
|
(Ok(value), Ok(label)) => options.push(SelectOption { value, label }),
|
||||||
|
(Err(error), _) | (_, Err(error)) => return Bound::Error(error),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Bound::Options(options)
|
||||||
|
}
|
||||||
|
}
|
||||||
110
crates/thing-core/src/command/capture.rs
Normal file
110
crates/thing-core/src/command/capture.rs
Normal file
|
|
@ -0,0 +1,110 @@
|
||||||
|
//! Captures: the values an invocation carries, read at the user's action from the drafts over the
|
||||||
|
//! bound values. An input beside a button in a Repeat row is found by scope: the activating node's
|
||||||
|
//! innermost instance first, then outward, then the declared id itself.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use thing_contract::{BoolValue, CapturedInput, ChoiceValue, CommandDecl, InputKind, InputValue, Node, NodeId, NumberValue, TextValue};
|
||||||
|
|
||||||
|
use crate::bind::{Bound, BoundTree, Field};
|
||||||
|
use crate::input::Drafts;
|
||||||
|
|
||||||
|
/// What the captures of one command came to: the values to send, and the drafts they were read from
|
||||||
|
/// (laid id and the value the table held), which a completed result clears if still held.
|
||||||
|
pub(super) struct Captured {
|
||||||
|
pub inputs: Vec<CapturedInput>,
|
||||||
|
pub held: Vec<(NodeId, InputValue)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The laid id of `declared` as seen from a node whose enclosing instance prefixes are `scope`
|
||||||
|
/// (innermost first): the most specific one the tree holds.
|
||||||
|
pub(super) fn laid_id(index: &HashMap<&NodeId, &Node>, scope: &[String], declared: &NodeId) -> Option<NodeId> {
|
||||||
|
(0..=scope.len())
|
||||||
|
.map(|start| NodeId::new(format!("{}{}", scope[start..].concat(), declared.as_str())))
|
||||||
|
.find(|candidate| index.contains_key(candidate))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn number(text: &str) -> Option<f64> {
|
||||||
|
text.trim().parse::<f64>().ok().filter(|value| value.is_finite())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The value one input sends: its draft when it has one of the right kind, else what it is bound to.
|
||||||
|
fn value(tree: &BoundTree, drafts: &Drafts, surface: &str, laid: &NodeId, node: &Node) -> Option<InputValue> {
|
||||||
|
let draft = drafts.get(surface, laid);
|
||||||
|
let bound = |field| tree.value(laid, field);
|
||||||
|
match node {
|
||||||
|
Node::Toggle(_) => match (draft, bound(Field::Checked)) {
|
||||||
|
(Some(InputValue::Bool(held)), _) => Some(InputValue::Bool(held.clone())),
|
||||||
|
(_, Some(Bound::Bool(checked))) => Some(InputValue::Bool(BoolValue { value: *checked })),
|
||||||
|
_ => None,
|
||||||
|
},
|
||||||
|
Node::Slider(_) => match (draft, bound(Field::Value)) {
|
||||||
|
(Some(InputValue::Number(held)), _) => Some(InputValue::Number(held.clone())),
|
||||||
|
(_, Some(Bound::Number(at))) => Some(InputValue::Number(NumberValue { value: *at })),
|
||||||
|
_ => None,
|
||||||
|
},
|
||||||
|
Node::Select(_) => match (draft, bound(Field::Selected)) {
|
||||||
|
(Some(InputValue::Choice(held)), _) => Some(InputValue::Choice(held.clone())),
|
||||||
|
(_, Some(Bound::Text(selected))) => Some(InputValue::Choice(ChoiceValue { value: selected.clone() })),
|
||||||
|
_ => None,
|
||||||
|
},
|
||||||
|
Node::TextInput(input) => {
|
||||||
|
let initial = match bound(Field::Initial) {
|
||||||
|
Some(Bound::Text(text)) => Some(text.as_str()),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
match input.input_kind {
|
||||||
|
InputKind::Text => match (draft, initial) {
|
||||||
|
(Some(InputValue::Text(held)), _) => Some(InputValue::Text(held.clone())),
|
||||||
|
(_, Some(text)) => Some(InputValue::Text(TextValue { value: text.to_string() })),
|
||||||
|
_ => None,
|
||||||
|
},
|
||||||
|
InputKind::Number => {
|
||||||
|
let typed = match draft {
|
||||||
|
Some(InputValue::Text(held)) => number(&held.value),
|
||||||
|
Some(InputValue::Number(held)) => Some(held.value).filter(|value| value.is_finite()),
|
||||||
|
_ => initial.and_then(number),
|
||||||
|
};
|
||||||
|
typed.map(|value| InputValue::Number(NumberValue { value }))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The captures of `decl`, in declared order, resolved from the scope of the activating node. The
|
||||||
|
/// error is the declared id of the first capture with no value to send.
|
||||||
|
pub(super) fn capture(tree: &BoundTree, drafts: &Drafts, surface: &str, scope: &[String], decl: &CommandDecl) -> Result<Captured, NodeId> {
|
||||||
|
let index = tree.index();
|
||||||
|
let mut captured = Captured { inputs: Vec::new(), held: Vec::new() };
|
||||||
|
for declared in &decl.captures {
|
||||||
|
let laid = laid_id(&index, scope, declared).ok_or_else(|| declared.clone())?;
|
||||||
|
let node = index.get(&laid).ok_or_else(|| declared.clone())?;
|
||||||
|
let value = value(tree, drafts, surface, &laid, node).ok_or_else(|| declared.clone())?;
|
||||||
|
captured.inputs.push(CapturedInput { node: declared.clone(), value });
|
||||||
|
if let Some(draft) = drafts.get(surface, &laid) {
|
||||||
|
captured.held.push((laid, draft.clone()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(captured)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The value a change input takes, or why it takes none. A slider is a range input: a value that is
|
||||||
|
/// not finite is refused, and a finite one outside its range is clamped to it. A select takes only an
|
||||||
|
/// option it declares (bound options included, as bound for this node).
|
||||||
|
pub(super) fn change(tree: &BoundTree, laid: &NodeId, node: &Node, value: &InputValue) -> Result<InputValue, &'static str> {
|
||||||
|
match (node, value) {
|
||||||
|
(Node::Slider(slider), InputValue::Number(at)) => {
|
||||||
|
if !at.value.is_finite() {
|
||||||
|
return Err("the slider value is not a finite number");
|
||||||
|
}
|
||||||
|
Ok(InputValue::Number(NumberValue { value: at.value.max(slider.min).min(slider.max) }))
|
||||||
|
}
|
||||||
|
(Node::Select(_), InputValue::Choice(chosen)) => match tree.value(laid, Field::Options) {
|
||||||
|
Some(Bound::Options(options)) if options.iter().any(|option| option.value == chosen.value) => Ok(value.clone()),
|
||||||
|
_ => Err("the choice names no declared option"),
|
||||||
|
},
|
||||||
|
_ => Ok(value.clone()),
|
||||||
|
}
|
||||||
|
}
|
||||||
183
crates/thing-core/src/command/lifecycle.rs
Normal file
183
crates/thing-core/src/command/lifecycle.rs
Normal file
|
|
@ -0,0 +1,183 @@
|
||||||
|
//! The invocation lifecycle: `Issued -> Pending* -> Completed | Denied | Failed`, with the core-only
|
||||||
|
//! terminal states `Malformed` and `TimedOut`. Terminal is final: a later result is a diagnostic,
|
||||||
|
//! never a state change. Core decides every transition; a provider only offers results.
|
||||||
|
|
||||||
|
use thing_contract::{CommandResult, DatabaseEntry, Outcome};
|
||||||
|
|
||||||
|
use super::{Commands, HostEffect, Live, Mark, State, capture, fault, validate};
|
||||||
|
use crate::bind::BoundTree;
|
||||||
|
use crate::diagnostic::{Code, Diagnostic};
|
||||||
|
use crate::input::Drafts;
|
||||||
|
use crate::port::{Change, Ledger, Record, StatePort};
|
||||||
|
use crate::time::Timestamp;
|
||||||
|
|
||||||
|
/// What one drained change did: the effects for the host to run, and what core says about it.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq)]
|
||||||
|
pub struct Answered {
|
||||||
|
pub effects: Vec<HostEffect>,
|
||||||
|
pub diagnostics: Vec<Diagnostic>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Commands {
|
||||||
|
/// One drained change. Only a command result is this module's; any other address is not and
|
||||||
|
/// answers empty. A result under no held invocation is `UnknownInvocation`, logged only.
|
||||||
|
/// `trees` finds a surface's bound tree by record key.
|
||||||
|
pub fn apply<'t>(
|
||||||
|
&mut self,
|
||||||
|
change: &Change,
|
||||||
|
now: Timestamp,
|
||||||
|
trees: &dyn Fn(&str) -> Option<&'t BoundTree>,
|
||||||
|
drafts: &mut Drafts,
|
||||||
|
port: &mut dyn StatePort,
|
||||||
|
ledger: &mut Ledger,
|
||||||
|
) -> Answered {
|
||||||
|
let mut answered = Answered::default();
|
||||||
|
let address = match change {
|
||||||
|
Change::Upsert(entry) => &entry.address,
|
||||||
|
Change::Delete(address) => address,
|
||||||
|
Change::Refused(refusal) => &refusal.address,
|
||||||
|
};
|
||||||
|
if address.schema.as_str() != CommandResult::SCHEMA_NAME {
|
||||||
|
return answered;
|
||||||
|
}
|
||||||
|
self.expire(now);
|
||||||
|
let Some(at) = self.live.iter().position(|live| live.interest.matches(address)) else {
|
||||||
|
if !matches!(change, Change::Delete(_)) {
|
||||||
|
answered.diagnostics.push(fault(
|
||||||
|
address.key.as_str(),
|
||||||
|
None,
|
||||||
|
Code::UnknownInvocation,
|
||||||
|
"no invocation of this id is held",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
return answered;
|
||||||
|
};
|
||||||
|
if matches!(change, Change::Delete(_)) {
|
||||||
|
return answered;
|
||||||
|
}
|
||||||
|
let surface = self.live[at].surface.clone();
|
||||||
|
let issuing = self.live[at].issuing.clone();
|
||||||
|
if self.live[at].state.is_terminal() {
|
||||||
|
answered.diagnostics.push(fault(&surface, issuing.as_ref(), Code::ResultAfterTerminal, "the invocation is already terminal"));
|
||||||
|
return answered;
|
||||||
|
}
|
||||||
|
let result = match change {
|
||||||
|
Change::Upsert(entry) => match &entry.record {
|
||||||
|
// One equality catches a body naming another invocation, and a seq that is not the key's.
|
||||||
|
Record::Result(result) if result.record_key() == address.key.as_str() => result,
|
||||||
|
Record::Result(_) => {
|
||||||
|
self.malformed(at, "the result is not the one its key names", now, &mut answered, port, ledger);
|
||||||
|
return answered;
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
self.malformed(at, "the record at a result address is not a result", now, &mut answered, port, ledger);
|
||||||
|
return answered;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
_ => {
|
||||||
|
self.malformed(at, "the result was refused at decode", now, &mut answered, port, ledger);
|
||||||
|
return answered;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let seq = result.seq().get();
|
||||||
|
if seq <= self.live[at].highest {
|
||||||
|
return answered;
|
||||||
|
}
|
||||||
|
self.live[at].highest = seq;
|
||||||
|
match result.outcome() {
|
||||||
|
Outcome::Pending(pending) => {
|
||||||
|
self.live[at].state = State::Pending(pending.message.clone());
|
||||||
|
self.live[at].deadline = now.plus_ms(self.timeout_ms);
|
||||||
|
}
|
||||||
|
Outcome::Completed(completed) => {
|
||||||
|
let effect = match &completed.effect {
|
||||||
|
None => None,
|
||||||
|
Some(effect) => match validate::effect(effect, trees(&surface), &self.live[at]) {
|
||||||
|
Ok(effect) => Some(effect),
|
||||||
|
Err(detail) => {
|
||||||
|
self.malformed(at, &detail, now, &mut answered, port, ledger);
|
||||||
|
return answered;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
if completed.clear_drafts {
|
||||||
|
drafts.clear_held(&surface, &self.live[at].held);
|
||||||
|
}
|
||||||
|
answered.effects.extend(effect);
|
||||||
|
self.settle(at, State::Completed, None, now, port, ledger);
|
||||||
|
}
|
||||||
|
Outcome::Denied(denied) => {
|
||||||
|
let mut target = issuing.clone();
|
||||||
|
if let Some(declared) = &denied.node {
|
||||||
|
let found = trees(&surface).and_then(|tree| capture::laid_id(&tree.index(), &self.live[at].scope, declared));
|
||||||
|
match found {
|
||||||
|
Some(laid) => target = Some(laid),
|
||||||
|
None => answered.diagnostics.push(fault(
|
||||||
|
&surface,
|
||||||
|
issuing.as_ref(),
|
||||||
|
Code::MalformedResult,
|
||||||
|
"denied node not in the surface",
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.settle(at, State::Denied, None, now, port, ledger);
|
||||||
|
if let Some(node) = target {
|
||||||
|
self.marks.insert((surface, node), Mark::Denied { reason: denied.reason.clone() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Outcome::Failed(failed) => {
|
||||||
|
self.settle(at, State::Failed, Some(Mark::Failed { reason: failed.reason.clone() }), now, port, ledger);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
answered
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Within a frame results apply before `tick` (`Core::frame` drains and applies, then ticks), so a
|
||||||
|
/// result queued for the frame its deadline passes wins over the timeout.
|
||||||
|
/// Move every non-terminal invocation whose deadline has come to `TimedOut`. A deadline is
|
||||||
|
/// compared with the time given: a wall clock that went backward delays a timeout, never fires one early.
|
||||||
|
pub fn tick(&mut self, now: Timestamp, port: &mut dyn StatePort, ledger: &mut Ledger) -> Vec<Diagnostic> {
|
||||||
|
self.expire(now);
|
||||||
|
let mut diagnostics = Vec::new();
|
||||||
|
for at in 0..self.live.len() {
|
||||||
|
let live = &self.live[at];
|
||||||
|
if !live.state.is_terminal() && live.deadline <= now {
|
||||||
|
diagnostics.push(fault(&live.surface, live.issuing.as_ref(), Code::InvocationTimedOut, "no result by the deadline"));
|
||||||
|
self.settle(at, State::TimedOut, Some(Mark::TimedOut), now, port, ledger);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
diagnostics
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The earliest deadline of an invocation still waiting; the frame's `next_wake`.
|
||||||
|
pub fn next_deadline(&self) -> Option<Timestamp> {
|
||||||
|
self.live.iter().filter(|live| !live.state.is_terminal()).map(|live: &Live| live.deadline).min()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A result core will not take: the invocation is `Malformed`, and nothing it carried runs.
|
||||||
|
fn malformed(&mut self, at: usize, detail: &str, now: Timestamp, answered: &mut Answered, port: &mut dyn StatePort, ledger: &mut Ledger) {
|
||||||
|
let live = &self.live[at];
|
||||||
|
answered.diagnostics.push(fault(&live.surface, live.issuing.as_ref(), Code::MalformedResult, detail));
|
||||||
|
self.settle(at, State::Malformed, Some(Mark::Malformed), now, port, ledger);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Forget the invocations that went terminal a whole timeout ago: a result after that is for an
|
||||||
|
/// invocation core no longer holds, so the table stays bounded by the work of one timeout. A
|
||||||
|
/// result inside the window is still judged against the invocation (`ResultAfterTerminal`).
|
||||||
|
fn expire(&mut self, now: Timestamp) {
|
||||||
|
let timeout = self.timeout_ms;
|
||||||
|
self.live.retain(|live| live.done.is_none_or(|done| now < done.plus_ms(timeout)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Enter a terminal state: the interest in results is released in the same call, and the
|
||||||
|
/// issuing node shows the mark.
|
||||||
|
fn settle(&mut self, at: usize, state: State, mark: Option<Mark>, now: Timestamp, port: &mut dyn StatePort, ledger: &mut Ledger) {
|
||||||
|
let live = &mut self.live[at];
|
||||||
|
live.state = state;
|
||||||
|
live.done = Some(now);
|
||||||
|
ledger.release(port, &live.interest);
|
||||||
|
if let (Some(mark), Some(node)) = (mark, &live.issuing) {
|
||||||
|
self.marks.insert((live.surface.clone(), node.clone()), mark);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
482
crates/thing-core/src/command/mod.rs
Normal file
482
crates/thing-core/src/command/mod.rs
Normal file
|
|
@ -0,0 +1,482 @@
|
||||||
|
//! Commands: the one owner of invocation minting, the invocation lifecycle and result validation.
|
||||||
|
//! It follows the Resolver and Binder: it is handed what the frame drained and never drains, reads
|
||||||
|
//! no clock (time is a parameter) and awaits nothing. Core writes no record but an invocation, and
|
||||||
|
//! that leaves through `take_outbound`, never through a port.
|
||||||
|
//!
|
||||||
|
//! Every way of minting (a press, a key, a confirmed dialog, a resume after an external step)
|
||||||
|
//! ends in `mint`. A user action mints one id; nothing re-mints.
|
||||||
|
|
||||||
|
mod capture;
|
||||||
|
mod lifecycle;
|
||||||
|
mod validate;
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use thing_contract::{
|
||||||
|
CapturedInput, CommandDecl, CommandId, CommandInvocation, CommandRef, CommandResult, DatabaseEntry, InputValue, Node, NodeId,
|
||||||
|
ProviderId, RecordPayload, SchemaId, Seq, Version,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::bind::{Bound, BoundTree, Field};
|
||||||
|
use crate::diagnostic::{Code, Diagnostic};
|
||||||
|
use crate::input::Drafts;
|
||||||
|
use crate::port::{IdSource, Interest, Ledger, Prefix, StatePort};
|
||||||
|
use crate::time::Timestamp;
|
||||||
|
|
||||||
|
pub use lifecycle::Answered;
|
||||||
|
|
||||||
|
/// The empty MessagePack array: a payload record with no slots. Thing Script has no payload source yet.
|
||||||
|
const EMPTY_PAYLOAD: [u8; 1] = [0x90];
|
||||||
|
|
||||||
|
/// What the user did to one node.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct Activation {
|
||||||
|
/// The laid id, instance ids included.
|
||||||
|
pub node: NodeId,
|
||||||
|
pub kind: ActivationKind,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub enum ActivationKind {
|
||||||
|
/// A Button or an Overlay's dismissal.
|
||||||
|
Press,
|
||||||
|
/// A Toggle, a Slider or a Select took a value; it is written to Drafts first, then the command fires.
|
||||||
|
Change(InputValue),
|
||||||
|
/// A TextInput's submit.
|
||||||
|
Submit,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the host runs for a provider's result. Closed.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub enum HostEffect {
|
||||||
|
OpenSurface { key: String },
|
||||||
|
OpenExternal { url: String, resume: Resume },
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The command to run when an external step returns. The host holds it across a navigation (the
|
||||||
|
/// session dies on `location.assign`) and hands it to `Core::resume`. `source` and `items` are the
|
||||||
|
/// invocation's, so a resumed command names the same row.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct Resume {
|
||||||
|
pub surface_key: String,
|
||||||
|
pub command: CommandId,
|
||||||
|
pub source: NodeId,
|
||||||
|
pub items: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a node shows a fault: the last terminal answer of an invocation issued from it, until it mints again.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub enum Mark {
|
||||||
|
Denied { reason: String },
|
||||||
|
Failed { reason: String },
|
||||||
|
Malformed,
|
||||||
|
TimedOut,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What render and accessibility read of one node. Derived from the live invocations; nothing is
|
||||||
|
/// stored on a node.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq)]
|
||||||
|
pub struct NodeState {
|
||||||
|
/// A non-terminal invocation was issued from this node.
|
||||||
|
pub busy: bool,
|
||||||
|
pub mark: Option<Mark>,
|
||||||
|
/// The message of the latest Pending result of a busy node's invocation.
|
||||||
|
pub pending: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq)]
|
||||||
|
pub struct NodeStates {
|
||||||
|
nodes: HashMap<NodeId, NodeState>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl NodeStates {
|
||||||
|
/// The state of a laid node; a node nothing happened to is the default.
|
||||||
|
pub fn get(&self, node: &NodeId) -> NodeState {
|
||||||
|
self.nodes.get(node).cloned().unwrap_or_default()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A command waiting for the user's yes. Its captures are the values at the user's action.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct Confirming {
|
||||||
|
pub surface: String,
|
||||||
|
pub node: NodeId,
|
||||||
|
pub command: CommandId,
|
||||||
|
pub text: String,
|
||||||
|
prepared: Prepared,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Confirming {
|
||||||
|
pub fn captured(&self) -> &[CapturedInput] {
|
||||||
|
&self.prepared.captured
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Everything an invocation is except its id and its time: what a confirm holds until the user answers.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
struct Prepared {
|
||||||
|
surface: String,
|
||||||
|
provider: ProviderId,
|
||||||
|
version: Version,
|
||||||
|
command: CommandId,
|
||||||
|
payload_schema: SchemaId,
|
||||||
|
captured: Vec<CapturedInput>,
|
||||||
|
held: Vec<(NodeId, InputValue)>,
|
||||||
|
source: NodeId,
|
||||||
|
items: Vec<String>,
|
||||||
|
/// The laid node the user acted on; a resume has none.
|
||||||
|
issuing: Option<NodeId>,
|
||||||
|
/// The instance prefixes around the issuing node, innermost first.
|
||||||
|
scope: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An invocation core issued. Terminal ones stay so a late result is judged, not lost.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
struct Live {
|
||||||
|
surface: String,
|
||||||
|
issuing: Option<NodeId>,
|
||||||
|
state: State,
|
||||||
|
/// The highest result `seq` taken.
|
||||||
|
highest: i32,
|
||||||
|
deadline: Timestamp,
|
||||||
|
/// When it went terminal; `None` while it waits.
|
||||||
|
done: Option<Timestamp>,
|
||||||
|
held: Vec<(NodeId, InputValue)>,
|
||||||
|
scope: Vec<String>,
|
||||||
|
interest: Interest,
|
||||||
|
source: NodeId,
|
||||||
|
items: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
enum State {
|
||||||
|
Issued,
|
||||||
|
Pending(String),
|
||||||
|
Completed,
|
||||||
|
Denied,
|
||||||
|
Failed,
|
||||||
|
Malformed,
|
||||||
|
TimedOut,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl State {
|
||||||
|
fn is_terminal(&self) -> bool {
|
||||||
|
!matches!(self, State::Issued | State::Pending(_))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Commands {
|
||||||
|
client: String,
|
||||||
|
timeout_ms: u32,
|
||||||
|
live: Vec<Live>,
|
||||||
|
marks: HashMap<(String, NodeId), Mark>,
|
||||||
|
confirming: Option<Confirming>,
|
||||||
|
outbound: Vec<CommandInvocation>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fault(surface: &str, node: Option<&NodeId>, code: Code, detail: impl Into<String>) -> Diagnostic {
|
||||||
|
Diagnostic { code, surface: surface.to_string(), node: node.cloned(), detail: detail.into() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An activation core did not act on; nothing was minted and no draft was written.
|
||||||
|
fn refused(surface: &str, node: &NodeId, detail: &str) -> Diagnostic {
|
||||||
|
fault(surface, Some(node), Code::ActivationRefused, detail)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A v4 UUID from 16 bytes: the version and variant bits are core's, so a minted id is always
|
||||||
|
/// UUID-shaped and dot-free (a result key splits at its last dot).
|
||||||
|
fn uuid(ids: &mut dyn IdSource) -> String {
|
||||||
|
let mut bytes = [0u8; 16];
|
||||||
|
ids.fill(&mut bytes);
|
||||||
|
bytes[6] = bytes[6] & 0x0f | 0x40;
|
||||||
|
bytes[8] = bytes[8] & 0x3f | 0x80;
|
||||||
|
let hex: String = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
|
||||||
|
format!("{}-{}-{}-{}-{}", &hex[0..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..32])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The key prefix every result of `invocation` shares, derived from the contract's one key
|
||||||
|
/// scheme: a result's key is this followed by its `seq`.
|
||||||
|
fn result_prefix(invocation: &CommandInvocation) -> String {
|
||||||
|
let key = CommandResult::pending(invocation, Seq::FIRST, "").record_key();
|
||||||
|
key[..key.rfind('.').map_or(key.len(), |dot| dot + 1)].to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The command a node fires for an activation, when the node takes that kind of activation.
|
||||||
|
fn command_of<'a>(node: &'a Node, kind: &ActivationKind) -> Option<&'a CommandRef> {
|
||||||
|
match (node, kind) {
|
||||||
|
(Node::Button(n), ActivationKind::Press) => Some(&n.on_activate),
|
||||||
|
(Node::Overlay(n), ActivationKind::Press) => Some(&n.dismiss),
|
||||||
|
(Node::TextInput(n), ActivationKind::Submit) => Some(&n.submit),
|
||||||
|
(Node::Toggle(n), ActivationKind::Change(InputValue::Bool(_))) => Some(&n.on_change),
|
||||||
|
(Node::Slider(n), ActivationKind::Change(InputValue::Number(_))) => Some(&n.commit),
|
||||||
|
(Node::Select(n), ActivationKind::Change(InputValue::Choice(_))) => Some(&n.on_change),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a command is fired from: the declared id of its source, and the instances around it.
|
||||||
|
struct Origin {
|
||||||
|
issuing: Option<NodeId>,
|
||||||
|
source: NodeId,
|
||||||
|
scope: Vec<String>,
|
||||||
|
items: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Commands {
|
||||||
|
pub fn new(client: impl Into<String>, timeout_ms: u32) -> Self {
|
||||||
|
Self {
|
||||||
|
client: client.into(),
|
||||||
|
timeout_ms,
|
||||||
|
live: Vec::new(),
|
||||||
|
marks: HashMap::new(),
|
||||||
|
confirming: None,
|
||||||
|
outbound: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one commit primitive: the user acted on `act.node` of `tree`. Every path calls it. It
|
||||||
|
/// mints one invocation, or nothing. A refusal (a node that is not a command source for this kind, a
|
||||||
|
/// node nobody laid, a change the input does not take, a command waiting on confirmation) answers with
|
||||||
|
/// a `Code::ActivationRefused` diagnostic. A disabled or busy button is not a refusal: the user sees
|
||||||
|
/// it, so it stays silent.
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub fn activate(
|
||||||
|
&mut self,
|
||||||
|
act: Activation,
|
||||||
|
tree: &BoundTree,
|
||||||
|
drafts: &mut Drafts,
|
||||||
|
now: Timestamp,
|
||||||
|
ids: &mut dyn IdSource,
|
||||||
|
port: &mut dyn StatePort,
|
||||||
|
ledger: &mut Ledger,
|
||||||
|
) -> Vec<Diagnostic> {
|
||||||
|
let surface = tree.resolved().document().record_key();
|
||||||
|
if let Some(waiting) = self.confirming_refusal(&surface, &act.node) {
|
||||||
|
return vec![waiting];
|
||||||
|
}
|
||||||
|
let Some(located) = tree.locate(&act.node) else {
|
||||||
|
return vec![refused(&surface, &act.node, "the node is not in the surface")];
|
||||||
|
};
|
||||||
|
// A Param command is the same refusal: resolve leaves none in a tree, so none reaches here.
|
||||||
|
let Some(CommandRef::Id(command)) = command_of(located.node, &act.kind) else {
|
||||||
|
return vec![refused(&surface, &act.node, "the node fires no command for this activation")];
|
||||||
|
};
|
||||||
|
if let ActivationKind::Change(value) = &act.kind {
|
||||||
|
// A control that takes no change holds no value the user did not send: the gate is before the draft.
|
||||||
|
if let Some(held) = self.refuses_change(tree, &act.node) {
|
||||||
|
return vec![held];
|
||||||
|
}
|
||||||
|
match capture::change(tree, &act.node, located.node, value) {
|
||||||
|
Ok(taken) => drafts.set(&surface, &act.node, taken),
|
||||||
|
Err(detail) => return vec![refused(&surface, &act.node, detail)],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.holds(tree, &act.node) {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
let Some(decl) = tree.resolved().document().commands.iter().find(|decl| decl.id == command.id) else {
|
||||||
|
return vec![fault(&surface, Some(&act.node), Code::UndeclaredCommand, "the command is not declared")];
|
||||||
|
};
|
||||||
|
let origin = Origin {
|
||||||
|
issuing: Some(act.node.clone()),
|
||||||
|
source: located.declared,
|
||||||
|
scope: located.prefixes,
|
||||||
|
items: located.items,
|
||||||
|
};
|
||||||
|
let prepared = match self.prepare(tree, drafts, decl, origin) {
|
||||||
|
Ok(prepared) => prepared,
|
||||||
|
Err(diagnostic) => return vec![diagnostic],
|
||||||
|
};
|
||||||
|
self.begin(prepared, act.node, decl.confirm.as_ref(), now, ids, port, ledger)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why `node` takes no change now, said as a refusal: a command waits for confirmation, or the
|
||||||
|
/// control is disabled, or its own invocation waits for a result. A change that is refused writes
|
||||||
|
/// no draft, so a control that looks disabled never holds a value that was not sent. A press on
|
||||||
|
/// such a control stays silent (`activate`); a change is an edit the user made and is told.
|
||||||
|
pub(crate) fn refuses_change(&self, tree: &BoundTree, node: &NodeId) -> Option<Diagnostic> {
|
||||||
|
let surface = tree.resolved().document().record_key();
|
||||||
|
if let Some(waiting) = self.confirming_refusal(&surface, node) {
|
||||||
|
return Some(waiting);
|
||||||
|
}
|
||||||
|
self.holds(tree, node).then(|| refused(&surface, node, "the control is disabled or waiting for a result"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn confirming_refusal(&self, surface: &str, node: &NodeId) -> Option<Diagnostic> {
|
||||||
|
self.confirming.is_some().then(|| refused(surface, node, "a command is waiting for confirmation"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `node` is a disabled Button or has an invocation waiting for its result.
|
||||||
|
fn holds(&self, tree: &BoundTree, node: &NodeId) -> bool {
|
||||||
|
let disabled = tree.value(node, Field::Enabled) == Some(&Bound::Bool(false));
|
||||||
|
disabled || self.busy(&tree.resolved().document().record_key(), node)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Answer the command waiting on confirmation. Accepting mints with the captures taken at the
|
||||||
|
/// user's action; rejecting drops it and draws no id.
|
||||||
|
pub fn confirm(&mut self, accept: bool, now: Timestamp, ids: &mut dyn IdSource, port: &mut dyn StatePort, ledger: &mut Ledger) {
|
||||||
|
if let Some(confirming) = self.confirming.take()
|
||||||
|
&& accept
|
||||||
|
{
|
||||||
|
self.mint(confirming.prepared, now, ids, port, ledger);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn confirming(&self) -> Option<&Confirming> {
|
||||||
|
self.confirming.as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run the command an external step named, as the invocation that asked for it: its declared
|
||||||
|
/// captures, its source and items, no issuing node (nothing is marked busy).
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub fn resume(
|
||||||
|
&mut self,
|
||||||
|
resume: &Resume,
|
||||||
|
tree: &BoundTree,
|
||||||
|
drafts: &Drafts,
|
||||||
|
now: Timestamp,
|
||||||
|
ids: &mut dyn IdSource,
|
||||||
|
port: &mut dyn StatePort,
|
||||||
|
ledger: &mut Ledger,
|
||||||
|
) -> Vec<Diagnostic> {
|
||||||
|
let surface = tree.resolved().document().record_key();
|
||||||
|
let decl = tree.resolved().document().commands.iter().find(|decl| decl.id == resume.command);
|
||||||
|
let (Some(decl), true) = (decl, surface == resume.surface_key) else {
|
||||||
|
return vec![fault(&surface, None, Code::UndeclaredCommand, "the command to resume is not declared at the held version")];
|
||||||
|
};
|
||||||
|
let scope = tree.locate_source(&resume.source, &resume.items).map(|located| located.prefixes).unwrap_or_default();
|
||||||
|
let origin = Origin { issuing: None, source: resume.source.clone(), scope, items: resume.items.clone() };
|
||||||
|
match self.prepare(tree, drafts, decl, origin) {
|
||||||
|
Ok(prepared) => self.begin(prepared, resume.source.clone(), decl.confirm.as_ref(), now, ids, port, ledger),
|
||||||
|
Err(diagnostic) => vec![diagnostic],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The invocations minted since the last call, in order.
|
||||||
|
pub fn take_outbound(&mut self) -> Vec<CommandInvocation> {
|
||||||
|
std::mem::take(&mut self.outbound)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What render and accessibility read for `surface`.
|
||||||
|
pub fn view(&self, surface: &str) -> NodeStates {
|
||||||
|
let mut nodes: HashMap<NodeId, NodeState> = HashMap::new();
|
||||||
|
for ((held, node), mark) in &self.marks {
|
||||||
|
if held == surface {
|
||||||
|
nodes.entry(node.clone()).or_default().mark = Some(mark.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for live in self.live.iter().filter(|live| live.surface == surface && !live.state.is_terminal()) {
|
||||||
|
if let Some(node) = &live.issuing {
|
||||||
|
let state = nodes.entry(node.clone()).or_default();
|
||||||
|
state.busy = true;
|
||||||
|
if let State::Pending(message) = &live.state {
|
||||||
|
state.pending = Some(message.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
NodeStates { nodes }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The surface is no longer shown: its invocations leave the table with their interests, its
|
||||||
|
/// marks go and a confirmation waiting on it is dropped.
|
||||||
|
pub fn forget(&mut self, surface: &str, port: &mut dyn StatePort, ledger: &mut Ledger) {
|
||||||
|
for live in self.live.iter().filter(|live| live.surface == surface && !live.state.is_terminal()) {
|
||||||
|
ledger.release(port, &live.interest);
|
||||||
|
}
|
||||||
|
self.live.retain(|live| live.surface != surface);
|
||||||
|
self.marks.retain(|(held, _), _| held != surface);
|
||||||
|
if self.confirming.as_ref().is_some_and(|confirming| confirming.surface == surface) {
|
||||||
|
self.confirming = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn busy(&self, surface: &str, node: &NodeId) -> bool {
|
||||||
|
self.live.iter().any(|live| !live.state.is_terminal() && live.surface == surface && live.issuing.as_ref() == Some(node))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn prepare(&self, tree: &BoundTree, drafts: &Drafts, decl: &CommandDecl, origin: Origin) -> Result<Prepared, Diagnostic> {
|
||||||
|
let document = tree.resolved().document();
|
||||||
|
let surface = document.record_key();
|
||||||
|
let captured = capture::capture(tree, drafts, &surface, &origin.scope, decl).map_err(|node| {
|
||||||
|
fault(&surface, Some(&node), Code::CaptureUnavailable, "the captured input has no value to send")
|
||||||
|
})?;
|
||||||
|
Ok(Prepared {
|
||||||
|
surface,
|
||||||
|
provider: document.provider_id.clone(),
|
||||||
|
version: document.version,
|
||||||
|
command: decl.id.clone(),
|
||||||
|
payload_schema: decl.payload_schema.clone(),
|
||||||
|
captured: captured.inputs,
|
||||||
|
held: captured.held,
|
||||||
|
source: origin.source,
|
||||||
|
items: origin.items,
|
||||||
|
issuing: origin.issuing,
|
||||||
|
scope: origin.scope,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where every way of acting on a command meets its confirmation: a command that asks waits for the
|
||||||
|
/// user's yes, holding the captures it was prepared with; any other mints. One command waits at a time.
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
fn begin(
|
||||||
|
&mut self,
|
||||||
|
prepared: Prepared,
|
||||||
|
node: NodeId,
|
||||||
|
confirm: Option<&String>,
|
||||||
|
now: Timestamp,
|
||||||
|
ids: &mut dyn IdSource,
|
||||||
|
port: &mut dyn StatePort,
|
||||||
|
ledger: &mut Ledger,
|
||||||
|
) -> Vec<Diagnostic> {
|
||||||
|
let Some(text) = confirm else {
|
||||||
|
self.mint(prepared, now, ids, port, ledger);
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
if self.confirming.is_some() {
|
||||||
|
return vec![refused(&prepared.surface, &node, "another command is waiting for confirmation")];
|
||||||
|
}
|
||||||
|
self.confirming = Some(Confirming { surface: prepared.surface.clone(), node, command: prepared.command.clone(), text: text.clone(), prepared });
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one mint: draw one id, hold the interest in its results before the host can send, and
|
||||||
|
/// queue the invocation.
|
||||||
|
fn mint(&mut self, prepared: Prepared, now: Timestamp, ids: &mut dyn IdSource, port: &mut dyn StatePort, ledger: &mut Ledger) {
|
||||||
|
let invocation = CommandInvocation {
|
||||||
|
invocation_id: uuid(ids),
|
||||||
|
surface_key: prepared.surface.clone(),
|
||||||
|
surface_version: prepared.version,
|
||||||
|
command: prepared.command,
|
||||||
|
payload: RecordPayload { schema: prepared.payload_schema, bytes: EMPTY_PAYLOAD.to_vec() },
|
||||||
|
captured: prepared.captured,
|
||||||
|
client: self.client.clone(),
|
||||||
|
issued_at: now.rfc3339(),
|
||||||
|
delegation: None,
|
||||||
|
source: prepared.source.clone(),
|
||||||
|
items: prepared.items.clone(),
|
||||||
|
};
|
||||||
|
let interest = Interest::Prefix(Prefix {
|
||||||
|
provider: prepared.provider,
|
||||||
|
schema: SchemaId::new(CommandResult::SCHEMA_NAME),
|
||||||
|
key_prefix: result_prefix(&invocation),
|
||||||
|
});
|
||||||
|
ledger.hold(port, &interest);
|
||||||
|
if let Some(node) = &prepared.issuing {
|
||||||
|
self.marks.remove(&(prepared.surface.clone(), node.clone()));
|
||||||
|
}
|
||||||
|
self.live.push(Live {
|
||||||
|
surface: prepared.surface,
|
||||||
|
issuing: prepared.issuing,
|
||||||
|
state: State::Issued,
|
||||||
|
highest: 0,
|
||||||
|
deadline: now.plus_ms(self.timeout_ms),
|
||||||
|
done: None,
|
||||||
|
held: prepared.held,
|
||||||
|
scope: prepared.scope,
|
||||||
|
interest,
|
||||||
|
source: prepared.source,
|
||||||
|
items: prepared.items,
|
||||||
|
});
|
||||||
|
self.outbound.push(invocation);
|
||||||
|
}
|
||||||
|
}
|
||||||
58
crates/thing-core/src/command/validate.rs
Normal file
58
crates/thing-core/src/command/validate.rs
Normal file
|
|
@ -0,0 +1,58 @@
|
||||||
|
//! What core will run for a provider's result: the closed effects, judged before any is emitted.
|
||||||
|
//! A provider decides what to ask; core decides whether it is allowed.
|
||||||
|
|
||||||
|
use thing_contract::{CommandId, CommandRef, Effect};
|
||||||
|
|
||||||
|
use super::{HostEffect, Live, Resume};
|
||||||
|
use crate::bind::BoundTree;
|
||||||
|
|
||||||
|
/// Whether `url` is absolute with the scheme http or https (ASCII case-insensitive) and a host.
|
||||||
|
fn web_url(url: &str) -> bool {
|
||||||
|
if url.chars().any(|c| c.is_control() || c.is_whitespace()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let Some((scheme, rest)) = url.split_once("://") else { return false };
|
||||||
|
(scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https"))
|
||||||
|
&& !rest.starts_with(['/', '?', '#'])
|
||||||
|
&& !rest.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The effect as data for the host, or why core refuses it. `tree` is the invocation's surface as
|
||||||
|
/// held now: a resume names a command that surface declares.
|
||||||
|
pub(super) fn effect(effect: &Effect, tree: Option<&BoundTree>, live: &Live) -> Result<HostEffect, String> {
|
||||||
|
match effect {
|
||||||
|
Effect::OpenSurface(open) => {
|
||||||
|
if open.key.starts_with("thing:surface:") {
|
||||||
|
Ok(HostEffect::OpenSurface { key: open.key.clone() })
|
||||||
|
} else {
|
||||||
|
Err("OpenSurface names a key that is not a surface".into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Effect::OpenExternal(open) => {
|
||||||
|
if !web_url(&open.url) {
|
||||||
|
return Err("OpenExternal names a url that is not absolute http or https".into());
|
||||||
|
}
|
||||||
|
let CommandRef::Id(resume) = &open.resume else {
|
||||||
|
return Err("OpenExternal resumes through a parameter".into());
|
||||||
|
};
|
||||||
|
let declared = tree.is_some_and(|tree| declares(tree, &resume.id));
|
||||||
|
if !declared {
|
||||||
|
return Err("OpenExternal resumes a command the surface does not declare".into());
|
||||||
|
}
|
||||||
|
Ok(HostEffect::OpenExternal {
|
||||||
|
url: open.url.clone(),
|
||||||
|
resume: Resume {
|
||||||
|
surface_key: live.surface.clone(),
|
||||||
|
command: resume.id.clone(),
|
||||||
|
source: live.source.clone(),
|
||||||
|
items: live.items.clone(),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn declares(tree: &BoundTree, command: &CommandId) -> bool {
|
||||||
|
tree.resolved().document().commands.iter().any(|decl| &decl.id == command)
|
||||||
|
}
|
||||||
|
|
||||||
83
crates/thing-core/src/diagnostic.rs
Normal file
83
crates/thing-core/src/diagnostic.rs
Normal file
|
|
@ -0,0 +1,83 @@
|
||||||
|
//! What core says about a document it could not take whole. The code set is closed: a later
|
||||||
|
//! cut adds its codes as reviewed changes, never as free strings.
|
||||||
|
|
||||||
|
use thing_contract::NodeId;
|
||||||
|
|
||||||
|
/// Why a document, or one node of it, was not taken as authored.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub enum Code {
|
||||||
|
/// The port refused the composition's bytes. A refusal is never absence.
|
||||||
|
DecodeRefused,
|
||||||
|
/// No composition is published at the named address.
|
||||||
|
UnresolvedUse,
|
||||||
|
/// A composition that uses itself through others, or a chain deeper than the limit.
|
||||||
|
CompositionCycle,
|
||||||
|
/// An argument, a body or a composition record that does not fit its Use.
|
||||||
|
CompositionInvalid,
|
||||||
|
/// A command no surface declaration names.
|
||||||
|
UndeclaredCommand,
|
||||||
|
/// Two nodes of the expanded tree share an id.
|
||||||
|
DuplicateNodeId,
|
||||||
|
/// A Param or a Slot outside any composition.
|
||||||
|
UnboundParam,
|
||||||
|
/// The expanded tree has too many nodes or is deeper than the depth rule.
|
||||||
|
ExpansionLimit,
|
||||||
|
/// The input nests deeper than the expander can recurse. A stack bound, not the depth rule: the depth
|
||||||
|
/// rule is judged on the finished tree and reports ExpansionLimit.
|
||||||
|
TooDeepToResolve,
|
||||||
|
/// A state record held under another schema than the Bind names.
|
||||||
|
BindSchemaMismatch,
|
||||||
|
/// An Image names a catalog or an asset the catalog does not hold.
|
||||||
|
AssetMissing,
|
||||||
|
/// A member path names a member the value does not have.
|
||||||
|
BindMemberMissing,
|
||||||
|
/// A value of another type than its site takes; no value is coerced.
|
||||||
|
BindTypeMismatch,
|
||||||
|
/// Two items of one Repeat share a key.
|
||||||
|
RepeatKeyDuplicate,
|
||||||
|
/// A surface offered at a version at or below one already offered; the held tree stays.
|
||||||
|
StaleVersionIgnored,
|
||||||
|
/// A style slot holding a value its CSS counterpart forbids; the slot took its initial value.
|
||||||
|
StyleValueInvalid,
|
||||||
|
/// A laid node reaches past the precision bound: the layout is refused, never rounded.
|
||||||
|
LayoutOutOfRange,
|
||||||
|
/// An Overlay anchored to a node that is not laid (hidden or absent); it was placed against the viewport.
|
||||||
|
OverlayAnchorMissing,
|
||||||
|
/// A colour or text token the theme does not hold; it drew as the fallback colour.
|
||||||
|
ThemeTokenUnknown,
|
||||||
|
/// A result that could not be taken: refused by decode, not a result, filed under another key than its
|
||||||
|
/// own, or carrying an effect core will not run. The invocation is Malformed.
|
||||||
|
MalformedResult,
|
||||||
|
/// A result under the result key space for an invocation core does not hold.
|
||||||
|
UnknownInvocation,
|
||||||
|
/// A result for an invocation already terminal; the state does not change.
|
||||||
|
ResultAfterTerminal,
|
||||||
|
/// An invocation with no result by its deadline; it is TimedOut.
|
||||||
|
InvocationTimedOut,
|
||||||
|
/// A capture whose input has no value to send (a bound error, absent, or a number that does not parse);
|
||||||
|
/// nothing was minted.
|
||||||
|
CaptureUnavailable,
|
||||||
|
/// A command capture naming no node, or a node that holds no input value.
|
||||||
|
CaptureUndeclared,
|
||||||
|
/// An activation core refused to act on: a kind the node does not take, a node nobody laid, a change
|
||||||
|
/// value outside what the input allows, a command blocked by a confirmation, or a resume that can no
|
||||||
|
/// longer run. Nothing was minted; the detail says which.
|
||||||
|
ActivationRefused,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Code {
|
||||||
|
/// Whether the fault leaves no tree (the whole document is refused) or only a placeholder.
|
||||||
|
pub fn refuses_document(self) -> bool {
|
||||||
|
matches!(self, Code::UndeclaredCommand | Code::DuplicateNodeId | Code::UnboundParam | Code::ExpansionLimit | Code::TooDeepToResolve | Code::CaptureUndeclared)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One fault. `detail` names the fault and never carries a state value.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct Diagnostic {
|
||||||
|
pub code: Code,
|
||||||
|
/// The record key of the surface the fault is in.
|
||||||
|
pub surface: String,
|
||||||
|
pub node: Option<NodeId>,
|
||||||
|
pub detail: String,
|
||||||
|
}
|
||||||
314
crates/thing-core/src/frame.rs
Normal file
314
crates/thing-core/src/frame.rs
Normal file
|
|
@ -0,0 +1,314 @@
|
||||||
|
//! The frame entry: one `Core::frame` call per frame the host makes drains the port, resolves,
|
||||||
|
//! binds, lays out and renders. Core owns the pipeline order and is the only caller of
|
||||||
|
//! `StatePort::drain`; it reads no clock, sleeps nowhere and never awaits. Later cuts extend
|
||||||
|
//! `frame` in place with their own step; there is no second entry.
|
||||||
|
|
||||||
|
use thing_contract::{CommandInvocation, DatabaseEntry, ProviderId, RecordKey, SchemaId, SurfaceDocument};
|
||||||
|
|
||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
|
use crate::bind::Binder;
|
||||||
|
use crate::command::{Activation, Commands, Confirming, HostEffect, Resume};
|
||||||
|
use crate::diagnostic::{Code, Diagnostic};
|
||||||
|
use crate::input::{Drafts, Input, InputEvent, Owners, Seen};
|
||||||
|
use crate::layout::{LaidTree, LayoutError, LayoutFrame, Measure, Metrics, layout};
|
||||||
|
use crate::port::{Address, Change, IdSource, Interest, Ledger, Lookup, StatePort};
|
||||||
|
use crate::render::{RenderCommand, RenderInput, Rendered, ScrollOffsets, Session, render};
|
||||||
|
use crate::resolve::{Limits, Resolver};
|
||||||
|
use crate::theme::Theme;
|
||||||
|
use crate::time::Timestamp;
|
||||||
|
|
||||||
|
/// What a core is built with. `metrics` is the mode of the one `Measure` core owns.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct Config {
|
||||||
|
pub limits: Limits,
|
||||||
|
pub metrics: Metrics,
|
||||||
|
/// How long an invocation waits for a result, and for the next one after a Pending (a heartbeat).
|
||||||
|
/// A guess, to be measured (build-spec O5).
|
||||||
|
pub invocation_timeout_ms: u32,
|
||||||
|
/// The kind of host core runs in (`renderer.web`, `renderer.tui`), written to every invocation. It
|
||||||
|
/// is never a caller identity: core has no identity to write, the transport sets it.
|
||||||
|
pub client: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Config {
|
||||||
|
pub fn new(metrics: Metrics, client: impl Into<String>) -> Self {
|
||||||
|
Self { limits: Limits::default(), metrics, invocation_timeout_ms: 15_000, client: client.into() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ports lent to one frame. The host owns its state port and changes it between frames;
|
||||||
|
/// it lends the same port every frame, because core's `Ledger` counts the subscriptions it made
|
||||||
|
/// on that port.
|
||||||
|
pub struct Ports<'a> {
|
||||||
|
pub state: &'a mut dyn StatePort,
|
||||||
|
pub ids: &'a mut dyn IdSource,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the host tells core each frame. `viewport` is the one writer of size: logical px
|
||||||
|
/// (`Metrics::Pixels`) or cells (`Metrics::Cells`), the space `LayoutFrame` takes; a resize is
|
||||||
|
/// the next frame's viewport.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct FrameInput {
|
||||||
|
pub now: Timestamp,
|
||||||
|
pub viewport: (f32, f32),
|
||||||
|
pub scale: f32,
|
||||||
|
pub events: Vec<InputEvent>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a frame hands back. Later cuts add fields; hosts keep compiling.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub struct FrameOutput {
|
||||||
|
pub commands: Vec<RenderCommand>,
|
||||||
|
pub diagnostics: Vec<Diagnostic>,
|
||||||
|
/// When the host should call `frame` again with nothing else to say; `None` while nothing in
|
||||||
|
/// core depends on time.
|
||||||
|
pub next_wake: Option<Timestamp>,
|
||||||
|
/// The invocations minted since the last frame, in order: core's only outbound write.
|
||||||
|
pub outbound: Vec<CommandInvocation>,
|
||||||
|
/// What the host runs for the results taken this frame.
|
||||||
|
pub effects: Vec<HostEffect>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Core {
|
||||||
|
metrics: Metrics,
|
||||||
|
measure: Box<dyn Measure>,
|
||||||
|
resolver: Resolver,
|
||||||
|
binder: Binder,
|
||||||
|
ledger: Ledger,
|
||||||
|
scroll: ScrollOffsets,
|
||||||
|
theme: Theme,
|
||||||
|
commands: Commands,
|
||||||
|
drafts: Drafts,
|
||||||
|
/// The pointer's press in progress.
|
||||||
|
input: Input,
|
||||||
|
/// What activations said since the last frame; the frame's diagnostics carry it out.
|
||||||
|
notes: Vec<Diagnostic>,
|
||||||
|
/// Resumes whose surface had not bound when the host handed them over; each runs at that surface's
|
||||||
|
/// first bind, or is dropped when the surface is left first.
|
||||||
|
held: Vec<Resume>,
|
||||||
|
/// The surface `show` named, and the one whose interest and trees are held.
|
||||||
|
wanted: Option<Address>,
|
||||||
|
shown: Option<Address>,
|
||||||
|
/// The last good frame: what the user saw, which hit-test reads.
|
||||||
|
last: Option<(LaidTree, Rendered)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Core {
|
||||||
|
pub fn new(config: Config, measure: Box<dyn Measure>) -> Self {
|
||||||
|
Self {
|
||||||
|
metrics: config.metrics,
|
||||||
|
measure,
|
||||||
|
resolver: Resolver::new(config.limits.clone()),
|
||||||
|
binder: Binder::new(config.limits),
|
||||||
|
ledger: Ledger::new(),
|
||||||
|
scroll: ScrollOffsets::default(),
|
||||||
|
theme: Theme::std(),
|
||||||
|
commands: Commands::new(config.client, config.invocation_timeout_ms),
|
||||||
|
drafts: Drafts::new(),
|
||||||
|
input: Input::new(),
|
||||||
|
notes: Vec::new(),
|
||||||
|
held: Vec::new(),
|
||||||
|
wanted: None,
|
||||||
|
shown: None,
|
||||||
|
last: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Name the one surface displayed. It takes effect at the next frame.
|
||||||
|
pub fn show(&mut self, provider: ProviderId, key: RecordKey) {
|
||||||
|
self.wanted = Some(Address { provider, schema: SchemaId::new(SurfaceDocument::SCHEMA_NAME), key });
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn frame(&mut self, input: FrameInput, ports: Ports<'_>) -> FrameOutput {
|
||||||
|
let FrameInput { now, viewport, scale, events } = input;
|
||||||
|
let port = ports.state;
|
||||||
|
// Input is judged entirely against the frame the user saw: its geometry and the values bound
|
||||||
|
// into it. Nothing of this frame (the surface it switches to, the provider updates it drains,
|
||||||
|
// the tree it binds) is in place yet, so no event reads a world the user did not look at.
|
||||||
|
let routed = self.route(&events, scale, now, ports.ids, port);
|
||||||
|
let mut changes = Vec::new();
|
||||||
|
if self.wanted != self.shown {
|
||||||
|
self.switch(port, &mut changes);
|
||||||
|
}
|
||||||
|
changes.extend(port.drain());
|
||||||
|
|
||||||
|
let mut diagnostics = std::mem::take(&mut self.notes);
|
||||||
|
diagnostics.extend(routed);
|
||||||
|
let mut effects = Vec::new();
|
||||||
|
let mut rebound = false;
|
||||||
|
for change in &changes {
|
||||||
|
let intake = self.resolver.apply(change, port, &mut self.ledger);
|
||||||
|
diagnostics.extend(intake.diagnostics);
|
||||||
|
for (key, replaced) in intake.changed {
|
||||||
|
if replaced {
|
||||||
|
if let Some(tree) = self.resolver.tree(&key).cloned() {
|
||||||
|
let bound = self.binder.bind(tree, port, &mut self.ledger);
|
||||||
|
rebound |= !bound.dirty.is_empty();
|
||||||
|
diagnostics.extend(bound.diagnostics);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.binder.forget(&key, port, &mut self.ledger);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let applied = self.binder.apply(change, port, &mut self.ledger);
|
||||||
|
rebound |= !applied.dirty.is_empty();
|
||||||
|
diagnostics.extend(applied.diagnostics);
|
||||||
|
let binder = &self.binder;
|
||||||
|
let answered = self.commands.apply(change, now, &|key| binder.tree(key), &mut self.drafts, port, &mut self.ledger);
|
||||||
|
diagnostics.extend(answered.diagnostics);
|
||||||
|
effects.extend(answered.effects);
|
||||||
|
}
|
||||||
|
if rebound {
|
||||||
|
self.retain_drafts();
|
||||||
|
}
|
||||||
|
for resume in std::mem::take(&mut self.held) {
|
||||||
|
match self.binder.tree(&resume.surface_key) {
|
||||||
|
Some(tree) => {
|
||||||
|
let said = self.commands.resume(&resume, tree, &self.drafts, now, ports.ids, port, &mut self.ledger);
|
||||||
|
diagnostics.extend(said);
|
||||||
|
}
|
||||||
|
None => self.held.push(resume),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Results of this frame are applied above, before the deadline is judged: a late result that was
|
||||||
|
// already queued wins over the timeout.
|
||||||
|
diagnostics.extend(self.commands.tick(now, port, &mut self.ledger));
|
||||||
|
|
||||||
|
let commands = self.draw(viewport, scale, &mut diagnostics);
|
||||||
|
FrameOutput {
|
||||||
|
commands,
|
||||||
|
diagnostics,
|
||||||
|
next_wake: self.commands.next_deadline(),
|
||||||
|
outbound: self.commands.take_outbound(),
|
||||||
|
effects,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The host's semantic activation: the user, or an accessibility action or an automation acting for
|
||||||
|
/// them, activated a node of the shown surface. It is the one primitive every input path ends in (pointer and
|
||||||
|
/// keyboard routes arrive here too). The invocation it mints is in the next
|
||||||
|
/// frame's `outbound`; a refusal (see `Commands::activate`) is said in that frame's `diagnostics`.
|
||||||
|
pub fn activate(&mut self, act: Activation, now: Timestamp, ports: Ports<'_>) {
|
||||||
|
let Some(tree) = self.shown.as_ref().and_then(|shown| self.binder.tree(shown.key.as_str())) else {
|
||||||
|
let node = Some(act.node);
|
||||||
|
self.notes.push(Diagnostic { code: Code::ActivationRefused, surface: String::new(), node, detail: "no surface is shown".into() });
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let said = self.commands.activate(act, tree, &mut self.drafts, now, ports.ids, ports.state, &mut self.ledger);
|
||||||
|
self.notes.extend(said);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Answer the command waiting on confirmation (`confirming`). The host shows the question and calls
|
||||||
|
/// this with the user's answer; accepting mints with the captures taken at the activation.
|
||||||
|
pub fn confirm(&mut self, accept: bool, now: Timestamp, ports: Ports<'_>) {
|
||||||
|
self.commands.confirm(accept, now, ports.ids, ports.state, &mut self.ledger);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The command waiting for the user's yes or no, for the host to ask.
|
||||||
|
pub fn confirming(&self) -> Option<&Confirming> {
|
||||||
|
self.commands.confirming()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run the command an `OpenExternal` effect named, once the external step has returned. The host
|
||||||
|
/// holds the `Resume` across the navigation and hands it back here; the command is minted, or asks
|
||||||
|
/// for confirmation, like an activation. A resume handed over before its surface has bound is held and
|
||||||
|
/// runs at the first bind; one whose surface is left first is dropped and said. Any other refusal is
|
||||||
|
/// said in the next frame's `diagnostics`.
|
||||||
|
pub fn resume(&mut self, resume: &Resume, now: Timestamp, ports: Ports<'_>) {
|
||||||
|
let Some(tree) = self.binder.tree(&resume.surface_key) else {
|
||||||
|
self.held.push(resume.clone());
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let said = self.commands.resume(resume, tree, &self.drafts, now, ports.ids, ports.state, &mut self.ledger);
|
||||||
|
self.notes.extend(said);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn route(&mut self, events: &[InputEvent], scale: f32, now: Timestamp, ids: &mut dyn IdSource, port: &mut dyn StatePort) -> Vec<Diagnostic> {
|
||||||
|
let mut said = Vec::new();
|
||||||
|
let (Some(shown), Some((laid, rendered))) = (&self.shown, &self.last) else { return said };
|
||||||
|
let Some(tree) = self.binder.tree(shown.key.as_str()) else { return said };
|
||||||
|
let line = self.theme.text.get("body").or_else(|| self.theme.text.get("thing.text")).map_or(16.0, |style| style.size);
|
||||||
|
let seen = Seen { rendered, laid, tree, metrics: self.metrics, scale, line };
|
||||||
|
let mut owners = Owners { commands: &mut self.commands, drafts: &mut self.drafts, scroll: &mut self.scroll, ids, port, ledger: &mut self.ledger };
|
||||||
|
for event in events {
|
||||||
|
said.extend(self.input.event(event, &seen, &mut owners, now));
|
||||||
|
}
|
||||||
|
said
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drop the drafts of nodes the shown surface no longer has.
|
||||||
|
fn retain_drafts(&mut self) {
|
||||||
|
let Some(shown) = &self.shown else { return };
|
||||||
|
let key = shown.key.as_str();
|
||||||
|
let live: HashSet<_> = match self.binder.tree(key) {
|
||||||
|
Some(tree) => tree.index().keys().map(|id| (*id).clone()).collect(),
|
||||||
|
None => HashSet::new(),
|
||||||
|
};
|
||||||
|
self.drafts.retain(key, &live);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Leave the surface shown and take the one wanted: the interest is held before the one read,
|
||||||
|
/// and what the read finds enters as a change like any republish.
|
||||||
|
fn switch(&mut self, port: &mut dyn StatePort, changes: &mut Vec<Change>) {
|
||||||
|
// A resume is for the surface it names: leaving for another one forgets it.
|
||||||
|
let wanted = self.wanted.as_ref().map(|address| address.key.as_str().to_string());
|
||||||
|
for resume in std::mem::take(&mut self.held) {
|
||||||
|
if wanted.as_deref() == Some(resume.surface_key.as_str()) {
|
||||||
|
self.held.push(resume);
|
||||||
|
} else {
|
||||||
|
let detail = "the surface was left before it bound; the resume is dropped";
|
||||||
|
self.notes.push(Diagnostic { code: Code::ActivationRefused, surface: resume.surface_key, node: Some(resume.source), detail: detail.into() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(old) = self.shown.take() {
|
||||||
|
self.input.cancel(old.key.as_str(), &mut self.drafts);
|
||||||
|
self.resolver.forget(old.key.as_str(), port, &mut self.ledger);
|
||||||
|
self.binder.forget(old.key.as_str(), port, &mut self.ledger);
|
||||||
|
self.commands.forget(old.key.as_str(), port, &mut self.ledger);
|
||||||
|
self.ledger.release(port, &Interest::Record(old));
|
||||||
|
self.scroll = ScrollOffsets::default();
|
||||||
|
self.last = None;
|
||||||
|
}
|
||||||
|
if let Some(new) = self.wanted.clone() {
|
||||||
|
self.ledger.hold(port, &Interest::Record(new.clone()));
|
||||||
|
match port.read(&new) {
|
||||||
|
Lookup::Present(entry) => changes.push(Change::Upsert(entry)),
|
||||||
|
Lookup::Refused(refusal) => changes.push(Change::Refused(refusal)),
|
||||||
|
Lookup::Absent => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.shown = self.wanted.clone();
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draw(&mut self, viewport: (f32, f32), scale: f32, diagnostics: &mut Vec<Diagnostic>) -> Vec<RenderCommand> {
|
||||||
|
let Some(address) = &self.shown else {
|
||||||
|
self.last = None;
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let Some(tree) = self.binder.tree(address.key.as_str()) else {
|
||||||
|
self.last = None;
|
||||||
|
return Vec::new();
|
||||||
|
};
|
||||||
|
let frame = LayoutFrame { viewport, scale, metrics: self.metrics };
|
||||||
|
match layout(tree, &frame, self.measure.as_mut()) {
|
||||||
|
Ok(laid) => {
|
||||||
|
let states = self.commands.view(address.key.as_str());
|
||||||
|
let session = Session::new(&self.drafts, &states);
|
||||||
|
let input = RenderInput { scale, metrics: self.metrics, viewport, scroll: &self.scroll, theme: &self.theme, session };
|
||||||
|
let rendered = render(tree, &laid, &input, self.measure.as_mut());
|
||||||
|
diagnostics.extend(rendered.diagnostics.iter().cloned());
|
||||||
|
let commands = rendered.commands.clone();
|
||||||
|
self.last = Some((laid, rendered));
|
||||||
|
commands
|
||||||
|
}
|
||||||
|
Err(LayoutError::OutOfRange(diagnostic)) => {
|
||||||
|
diagnostics.push(diagnostic);
|
||||||
|
self.last.as_ref().map(|(_, rendered)| rendered.commands.clone()).unwrap_or_default()
|
||||||
|
}
|
||||||
|
// The host's room, not a document fault: nothing is drawn and the last good frame stays.
|
||||||
|
Err(LayoutError::Frame(_)) => Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
82
crates/thing-core/src/input/drafts.rs
Normal file
82
crates/thing-core/src/input/drafts.rs
Normal file
|
|
@ -0,0 +1,82 @@
|
||||||
|
//! Drafts: the one owner of every input node's uncommitted value, keyed (surface key, laid node id).
|
||||||
|
//! A value enters when the user changes an input and leaves when a result clears it or a republish
|
||||||
|
//! removes its node. Nothing else in core, and no host, keeps a second copy.
|
||||||
|
|
||||||
|
use std::borrow::Cow;
|
||||||
|
use std::collections::{HashMap, HashSet};
|
||||||
|
|
||||||
|
use thing_contract::{InputValue, NodeId};
|
||||||
|
|
||||||
|
use crate::bind::{Bound, BoundTree, Field};
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq)]
|
||||||
|
pub struct Drafts {
|
||||||
|
values: HashMap<(String, NodeId), InputValue>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drafts {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn set(&mut self, surface: &str, node: &NodeId, value: InputValue) {
|
||||||
|
self.values.insert((surface.to_string(), node.clone()), value);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(&self, surface: &str, node: &NodeId) -> Option<&InputValue> {
|
||||||
|
self.values.get(&(surface.to_string(), node.clone()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Put `node`'s draft back to what it was before a press wrote it: `None` leaves it with none.
|
||||||
|
pub fn restore(&mut self, surface: &str, node: &NodeId, prior: Option<InputValue>) {
|
||||||
|
let key = (surface.to_string(), node.clone());
|
||||||
|
match prior {
|
||||||
|
Some(value) => self.values.insert(key, value),
|
||||||
|
None => self.values.remove(&key),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drop each draft in `held` that the table still holds with that value. A draft edited since it
|
||||||
|
/// was held is newer than what was sent, and stays; a node with no draft is untouched.
|
||||||
|
pub fn clear_held(&mut self, surface: &str, held: &[(NodeId, InputValue)]) {
|
||||||
|
for (node, value) in held {
|
||||||
|
let key = (surface.to_string(), node.clone());
|
||||||
|
if self.values.get(&key) == Some(value) {
|
||||||
|
self.values.remove(&key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Keep only the drafts of `surface` whose node is in `live` (the ids of the republished tree);
|
||||||
|
/// other surfaces' drafts stay.
|
||||||
|
pub fn retain(&mut self, surface: &str, live: &HashSet<NodeId>) {
|
||||||
|
self.values.retain(|(held, node), _| held != surface || live.contains(node));
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn len(&self) -> usize {
|
||||||
|
self.values.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.values.is_empty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a node's site currently shows: the draft over the bound value. The one place that rule is
|
||||||
|
/// written, read by render (through its `Session`) and by pointer input (a Toggle flips what is shown).
|
||||||
|
/// Only a draft of the site's own kind counts: a Number draft in a TextInput shows as its number.
|
||||||
|
pub fn current<'a>(tree: &'a BoundTree, drafts: Option<&'a Drafts>, node: &NodeId, field: Field) -> Option<Cow<'a, Bound>> {
|
||||||
|
let draft = drafts.and_then(|drafts| drafts.get(&tree.resolved().document().record_key(), node));
|
||||||
|
let shown = match (field, draft) {
|
||||||
|
(Field::Checked, Some(InputValue::Bool(held))) => Some(Bound::Bool(held.value)),
|
||||||
|
(Field::Value, Some(InputValue::Number(held))) => Some(Bound::Number(held.value)),
|
||||||
|
(Field::Selected, Some(InputValue::Choice(held))) => Some(Bound::Text(held.value.clone())),
|
||||||
|
(Field::Initial, Some(InputValue::Text(held))) => Some(Bound::Text(held.value.clone())),
|
||||||
|
(Field::Initial, Some(InputValue::Number(held))) => Some(Bound::Text(held.value.to_string())),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
match shown {
|
||||||
|
Some(bound) => Some(Cow::Owned(bound)),
|
||||||
|
None => tree.value(node, field).map(Cow::Borrowed),
|
||||||
|
}
|
||||||
|
}
|
||||||
83
crates/thing-core/src/input/event.rs
Normal file
83
crates/thing-core/src/input/event.rs
Normal file
|
|
@ -0,0 +1,83 @@
|
||||||
|
//! The closed input model every host speaks to core. It is not `#[non_exhaustive]`: a new
|
||||||
|
//! variant is a contract revision every host compiles against.
|
||||||
|
//!
|
||||||
|
//! The viewport and the scale are not events: they are `FrameInput` fields, and a resize is the
|
||||||
|
//! next frame's viewport. Time is not an event either (`FrameInput::now`).
|
||||||
|
|
||||||
|
/// One thing the user did, in the order the host saw it.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub enum InputEvent {
|
||||||
|
/// A key press or auto-repeat (`repeat: true`). A release never enters: a terminal
|
||||||
|
/// reports Release on Windows and the TUI drops it, and the web host drops keyup. `Char` is the
|
||||||
|
/// character the keyboard layout produced (Shift+a is `Char('A')` with `shift` set;
|
||||||
|
/// Shift+Tab is `Tab` with `shift`). A typing key emits `Key` then `Text`, in that order (DOM
|
||||||
|
/// keydown precedes beforeinput; a window system's key event carries text beside the key; egui emits
|
||||||
|
/// Event::Key then Event::Text); a Ctrl or Alt chord emits `Key` only. Commands bind to `Key`.
|
||||||
|
Key { key: Key, modifiers: Modifiers, repeat: bool },
|
||||||
|
/// Committed text to insert; a paste is `Text`. Text inserts only from `Text`, so nothing
|
||||||
|
/// inserts twice.
|
||||||
|
Text(String),
|
||||||
|
/// The IME preedit, replacing any earlier one; empty `text` ends it without commit, and the
|
||||||
|
/// commit arrives as `Text` (DOM compositionupdate/compositionend; a window system's IME preedit and commit).
|
||||||
|
/// `cursor` is UTF-8 byte offsets into `text`, the window-system convention; the web host converts the
|
||||||
|
/// DOM's UTF-16 offsets.
|
||||||
|
Compose { text: String, cursor: Option<(u32, u32)> },
|
||||||
|
/// `at` is in the space `Placed` is in: logical px, or cells where a terminal cell
|
||||||
|
/// `(col, row)` is its centre `(col + 0.5, row + 0.5)`, the point the TUI's paint covers a
|
||||||
|
/// cell by, so a hit and a drawn cell agree.
|
||||||
|
PointerDown { at: (f32, f32), button: PointerButton, modifiers: Modifiers },
|
||||||
|
/// Sent with or without a button held.
|
||||||
|
PointerMove { at: (f32, f32), modifiers: Modifiers },
|
||||||
|
PointerUp { at: (f32, f32), button: PointerButton, modifiers: Modifiers },
|
||||||
|
/// The platform took the pointer (DOM pointercancel; the web host uses setPointerCapture so
|
||||||
|
/// an up outside the canvas still arrives): a pending press is dropped and no up follows.
|
||||||
|
PointerCancel,
|
||||||
|
/// `delta` positive y moves content toward its end (the scroll offset grows), positive x
|
||||||
|
/// right: the DOM WheelEvent sign. A terminal's ScrollDown is `(0, 1)` `Lines`; a
|
||||||
|
/// window system whose line delta has the opposite sign is negated by its host. `Units` are logical px or
|
||||||
|
/// cells; `Lines` are converted by core.
|
||||||
|
Wheel { at: (f32, f32), delta: (f32, f32), unit: WheelUnit, modifiers: Modifiers },
|
||||||
|
/// The host window or terminal gained (`true`) or lost focus.
|
||||||
|
Focus(bool),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub enum Key {
|
||||||
|
Char(char),
|
||||||
|
Enter,
|
||||||
|
Tab,
|
||||||
|
Backspace,
|
||||||
|
Delete,
|
||||||
|
Escape,
|
||||||
|
Left,
|
||||||
|
Right,
|
||||||
|
Up,
|
||||||
|
Down,
|
||||||
|
Home,
|
||||||
|
End,
|
||||||
|
PageUp,
|
||||||
|
PageDown,
|
||||||
|
Insert,
|
||||||
|
F(u8),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||||
|
pub struct Modifiers {
|
||||||
|
pub shift: bool,
|
||||||
|
pub ctrl: bool,
|
||||||
|
pub alt: bool,
|
||||||
|
pub meta: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub enum PointerButton {
|
||||||
|
Primary,
|
||||||
|
Secondary,
|
||||||
|
Middle,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub enum WheelUnit {
|
||||||
|
Units,
|
||||||
|
Lines,
|
||||||
|
}
|
||||||
102
crates/thing-core/src/input/hit.rs
Normal file
102
crates/thing-core/src/input/hit.rs
Normal file
|
|
@ -0,0 +1,102 @@
|
||||||
|
//! Hit-testing: which node a point reaches, read from the geometry render placed and nothing else.
|
||||||
|
//! The point is in the space `Placed` is in (logical px, or cells), so this file applies no scroll or
|
||||||
|
//! clip of its own: render already did, and `Placed::visible` is what the user could see. `k` (device px
|
||||||
|
//! per logical px, from `render::device_scale`) only puts point and edges on the device grid layout laid.
|
||||||
|
//! Paint order is the only layer order: the last placed node under the point wins, overlays are last,
|
||||||
|
//! and a modal overlay shuts out everything painted before it.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use thing_contract::{Node, NodeId};
|
||||||
|
|
||||||
|
use crate::layout::{LaidTree, Rect};
|
||||||
|
use crate::render::Rendered;
|
||||||
|
|
||||||
|
/// What a press can activate: a control, or a modal's scrim (its dismissal).
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub(super) enum Control {
|
||||||
|
Button,
|
||||||
|
Toggle,
|
||||||
|
Slider,
|
||||||
|
Select,
|
||||||
|
TextInput,
|
||||||
|
Scrim,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub(super) struct Target {
|
||||||
|
pub(super) node: NodeId,
|
||||||
|
pub(super) control: Control,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a point lands before any node is asked what it takes: the topmost node under it, or the
|
||||||
|
/// modal overlay (by laid index) when the point reaches nothing inside it.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub(super) enum Reach {
|
||||||
|
Node(usize),
|
||||||
|
Scrim(usize),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A coordinate on the device grid, held to 1/1024 px. Layout lays whole device pixels, render divides
|
||||||
|
/// them by the scale, and a pointer is that logical coordinate again: `k` times it is the device pixel
|
||||||
|
/// only up to the rounding error of dividing and multiplying back, which at a fractional scale is enough to
|
||||||
|
/// put the first pixel past an edge inside it. The grid is coarser than that error and finer than any
|
||||||
|
/// pixel, so an edge and a pointer that mean the same device position compare equal.
|
||||||
|
fn on_device(logical: f32, k: f32) -> f32 {
|
||||||
|
const GRID: f32 = 1024.0;
|
||||||
|
(logical * k * GRID).round() / GRID
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Half-open on the device grid: a node's right and bottom edges belong to its neighbour.
|
||||||
|
fn covers(rect: Rect, (x, y): (f32, f32), k: f32) -> bool {
|
||||||
|
let (x, y) = (on_device(x, k), on_device(y, k));
|
||||||
|
x >= on_device(rect.x, k) && x < on_device(rect.x + rect.w, k) && y >= on_device(rect.y, k) && y < on_device(rect.y + rect.h, k)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn reach(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeId, &Node>, point: (f32, f32), k: f32) -> Option<Reach> {
|
||||||
|
// The last modal overlay root in paint order: nothing painted before it is reachable, and what
|
||||||
|
// is painted after it (its own subtree, then any later overlay) is.
|
||||||
|
let modal = laid
|
||||||
|
.nodes
|
||||||
|
.iter()
|
||||||
|
.rposition(|node| node.parent.is_none() && matches!(index.get(&node.id), Some(Node::Overlay(overlay)) if overlay.modal));
|
||||||
|
let floor = modal.map_or(0, |m| m + 1);
|
||||||
|
// A non-modal overlay's root is only where its content is anchored: it is the viewport or the
|
||||||
|
// anchor's rect, not something drawn, so a press that misses the content goes on through it.
|
||||||
|
let transparent = |i: usize| laid.nodes[i].parent.is_none() && matches!(index.get(&laid.nodes[i].id), Some(Node::Overlay(_)));
|
||||||
|
let top = rendered.placed.iter().enumerate().skip(floor).rev().find(|(i, placed)| !transparent(*i) && placed.visible.is_some_and(|seen| covers(seen, point, k)));
|
||||||
|
match (top, modal) {
|
||||||
|
(Some((i, _)), _) => Some(Reach::Node(i)),
|
||||||
|
(None, Some(m)) => Some(Reach::Scrim(m)),
|
||||||
|
(None, None) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn control_of(node: &Node) -> Option<Control> {
|
||||||
|
match node {
|
||||||
|
Node::Button(_) => Some(Control::Button),
|
||||||
|
Node::Toggle(_) => Some(Control::Toggle),
|
||||||
|
Node::Slider(_) => Some(Control::Slider),
|
||||||
|
Node::Select(_) => Some(Control::Select),
|
||||||
|
Node::TextInput(_) => Some(Control::TextInput),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The node `point` activates: the nearest activatable node at or above the topmost one under it
|
||||||
|
/// (a Button's label hits the Button), or a modal's scrim. A point on a Box, on text outside a
|
||||||
|
/// control or on a non-modal overlay's root targets nothing.
|
||||||
|
pub(super) fn target(rendered: &Rendered, laid: &LaidTree, index: &HashMap<&NodeId, &Node>, point: (f32, f32), k: f32) -> Option<Target> {
|
||||||
|
let mut at = match reach(rendered, laid, index, point, k)? {
|
||||||
|
Reach::Scrim(m) => return Some(Target { node: laid.nodes[m].id.clone(), control: Control::Scrim }),
|
||||||
|
Reach::Node(i) => Some(i),
|
||||||
|
};
|
||||||
|
while let Some(i) = at {
|
||||||
|
let laid_node = laid.nodes.get(i)?;
|
||||||
|
if let Some(control) = index.get(&laid_node.id).copied().and_then(control_of) {
|
||||||
|
return Some(Target { node: laid_node.id.clone(), control });
|
||||||
|
}
|
||||||
|
at = laid_node.parent.map(|parent| parent as usize);
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
16
crates/thing-core/src/input/mod.rs
Normal file
16
crates/thing-core/src/input/mod.rs
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
//! What a host tells core about its user: the closed `InputEvent` vocabulary, the `Drafts` table
|
||||||
|
//! that owns what the user has typed or chosen and not yet sent, hit-testing against the frame the
|
||||||
|
//! user saw, and the pointer routes that turn a press, a drag or a wheel into an activation, a draft
|
||||||
|
//! or a scroll offset.
|
||||||
|
|
||||||
|
pub mod drafts;
|
||||||
|
pub mod event;
|
||||||
|
mod hit;
|
||||||
|
mod pointer;
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests;
|
||||||
|
|
||||||
|
pub use drafts::{Drafts, current};
|
||||||
|
pub use event::{InputEvent, Key, Modifiers, PointerButton, WheelUnit};
|
||||||
|
pub(crate) use pointer::{Input, Owners, Seen};
|
||||||
210
crates/thing-core/src/input/pointer.rs
Normal file
210
crates/thing-core/src/input/pointer.rs
Normal file
|
|
@ -0,0 +1,210 @@
|
||||||
|
//! Pointer input: press state and the routes from a pointer event to the one activation primitive,
|
||||||
|
//! to `Drafts` (a Slider drag) and to `ScrollOffsets` (the wheel). Input decides which node an
|
||||||
|
//! event reaches and nothing about what a command does: every commit ends in `Commands::activate`.
|
||||||
|
|
||||||
|
use thing_contract::{BoolValue, InputValue, Node, NodeId, NumberValue, SliderNode};
|
||||||
|
|
||||||
|
use super::drafts::{Drafts, current};
|
||||||
|
use super::event::{InputEvent, PointerButton, WheelUnit};
|
||||||
|
use super::hit::{Control, Reach, Target, reach, target};
|
||||||
|
use crate::bind::{Bound, BoundTree, Field};
|
||||||
|
use crate::command::{Activation, ActivationKind, Commands};
|
||||||
|
use crate::diagnostic::Diagnostic;
|
||||||
|
use crate::layout::{LaidTree, Metrics, Rect};
|
||||||
|
use crate::port::{IdSource, Ledger, StatePort};
|
||||||
|
use crate::render::{Rendered, ScrollOffsets, clamp, device_scale};
|
||||||
|
use crate::time::Timestamp;
|
||||||
|
|
||||||
|
/// The last good frame and how it was drawn: what every event is judged against.
|
||||||
|
pub(crate) struct Seen<'a> {
|
||||||
|
pub(crate) rendered: &'a Rendered,
|
||||||
|
pub(crate) laid: &'a LaidTree,
|
||||||
|
pub(crate) tree: &'a BoundTree,
|
||||||
|
pub(crate) metrics: Metrics,
|
||||||
|
/// Device px per logical px (Pixels), which turns a wheel's logical units into the device px
|
||||||
|
/// scroll offsets are held in.
|
||||||
|
pub(crate) scale: f32,
|
||||||
|
/// The theme's body text size in logical px: what one wheel line is in Pixels. A guess, unmeasured.
|
||||||
|
pub(crate) line: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Seen<'_> {
|
||||||
|
/// Device px per logical px, which is what a pointer is multiplied by to land on laid pixels.
|
||||||
|
fn k(&self) -> f32 {
|
||||||
|
device_scale(self.metrics, self.scale)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The owners an event writes through: activation, drafts and scroll positions.
|
||||||
|
pub(crate) struct Owners<'a> {
|
||||||
|
pub(crate) commands: &'a mut Commands,
|
||||||
|
pub(crate) drafts: &'a mut Drafts,
|
||||||
|
pub(crate) scroll: &'a mut ScrollOffsets,
|
||||||
|
pub(crate) ids: &'a mut dyn IdSource,
|
||||||
|
pub(crate) port: &'a mut dyn StatePort,
|
||||||
|
pub(crate) ledger: &'a mut Ledger,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one press in progress. A Slider's press also holds the draft it replaced, so a cancel can put it back.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
enum Press {
|
||||||
|
Target(Target),
|
||||||
|
Drag { node: NodeId, prior: Option<InputValue> },
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The owner of press state. No node holds a pressed or hover flag.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq)]
|
||||||
|
struct Pointer {
|
||||||
|
press: Option<Press>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The routes every pointer and wheel event takes; it owns the `Pointer`.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq)]
|
||||||
|
pub(crate) struct Input {
|
||||||
|
pointer: Pointer,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The value a press at `x` on a Slider's track `rect` chooses: along `[min, max]`, snapped to `step`
|
||||||
|
/// from `min`, held in range. None when the slider has no usable range or track.
|
||||||
|
fn slider_value(slider: &SliderNode, rect: Rect, x: f32) -> Option<f64> {
|
||||||
|
if !(slider.min.is_finite() && slider.max.is_finite() && slider.min < slider.max && rect.w > 0.0 && x.is_finite()) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let along = f64::from((x - rect.x) / rect.w);
|
||||||
|
let raw = slider.min + along * (slider.max - slider.min);
|
||||||
|
let snapped = if slider.step.is_finite() && slider.step > 0.0 { slider.min + ((raw - slider.min) / slider.step).round() * slider.step } else { raw };
|
||||||
|
Some(snapped.clamp(slider.min, slider.max))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn placed_rect(rendered: &Rendered, node: &NodeId) -> Option<Rect> {
|
||||||
|
rendered.placed.iter().find(|placed| &placed.id == node).map(|placed| placed.rect)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Input {
|
||||||
|
pub(crate) fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drop the press in progress, as the platform taking the pointer does, and as leaving the
|
||||||
|
/// surface does: a Slider draft the press wrote goes back to what it was.
|
||||||
|
pub(crate) fn cancel(&mut self, surface: &str, drafts: &mut Drafts) {
|
||||||
|
if let Some(Press::Drag { node, prior }) = self.pointer.press.take() {
|
||||||
|
drafts.restore(surface, &node, prior);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Route one event. Keys, text, composition and the window gaining or losing the user are not pointer input and change nothing,
|
||||||
|
/// and only the primary button presses. The diagnostics are the activations' refusals.
|
||||||
|
pub(crate) fn event(&mut self, event: &InputEvent, seen: &Seen<'_>, owners: &mut Owners<'_>, now: Timestamp) -> Vec<Diagnostic> {
|
||||||
|
let surface = seen.tree.resolved().document().record_key();
|
||||||
|
match event {
|
||||||
|
InputEvent::PointerDown { at, button: PointerButton::Primary, .. } => return self.down(*at, seen, owners, &surface),
|
||||||
|
InputEvent::PointerMove { at, .. } => return self.drag(*at, seen, owners, &surface),
|
||||||
|
InputEvent::PointerUp { at, button: PointerButton::Primary, .. } => return self.up(*at, seen, owners, now, &surface),
|
||||||
|
InputEvent::PointerCancel => self.cancel(&surface, owners.drafts),
|
||||||
|
InputEvent::Wheel { at, delta, unit, .. } => wheel(*at, *delta, *unit, seen, owners.scroll),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn down(&mut self, at: (f32, f32), seen: &Seen<'_>, owners: &mut Owners<'_>, surface: &str) -> Vec<Diagnostic> {
|
||||||
|
// A press never starts over another: the one in progress ends first.
|
||||||
|
self.cancel(surface, owners.drafts);
|
||||||
|
let index = seen.tree.index();
|
||||||
|
let mut said = Vec::new();
|
||||||
|
self.pointer.press = target(seen.rendered, seen.laid, &index, at, seen.k()).and_then(|hit| match (hit.control, index.get(&hit.node)) {
|
||||||
|
(Control::Slider, Some(Node::Slider(slider))) => {
|
||||||
|
let value = placed_rect(seen.rendered, &hit.node).and_then(|rect| slider_value(slider, rect, at.0))?;
|
||||||
|
// A slider that takes no change takes no press: nothing is drafted, so nothing is left unsent.
|
||||||
|
if let Some(held) = owners.commands.refuses_change(seen.tree, &hit.node) {
|
||||||
|
said.push(held);
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let prior = owners.drafts.get(surface, &hit.node).cloned();
|
||||||
|
owners.drafts.set(surface, &hit.node, InputValue::Number(NumberValue { value }));
|
||||||
|
Some(Press::Drag { node: hit.node, prior })
|
||||||
|
}
|
||||||
|
_ => Some(Press::Target(hit)),
|
||||||
|
});
|
||||||
|
said
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drag(&mut self, at: (f32, f32), seen: &Seen<'_>, owners: &mut Owners<'_>, surface: &str) -> Vec<Diagnostic> {
|
||||||
|
let Some(Press::Drag { node, .. }) = &self.pointer.press else { return Vec::new() };
|
||||||
|
let index = seen.tree.index();
|
||||||
|
let Some(Node::Slider(slider)) = index.get(node) else { return Vec::new() };
|
||||||
|
if let Some(held) = owners.commands.refuses_change(seen.tree, node) {
|
||||||
|
return vec![held];
|
||||||
|
}
|
||||||
|
if let Some(value) = placed_rect(seen.rendered, node).and_then(|rect| slider_value(slider, rect, at.0)) {
|
||||||
|
owners.drafts.set(surface, node, InputValue::Number(NumberValue { value }));
|
||||||
|
}
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn up(&mut self, at: (f32, f32), seen: &Seen<'_>, owners: &mut Owners<'_>, now: Timestamp, surface: &str) -> Vec<Diagnostic> {
|
||||||
|
let activation = match self.pointer.press.take() {
|
||||||
|
None => return Vec::new(),
|
||||||
|
// A drag commits the draft it wrote, wherever the pointer is let go.
|
||||||
|
Some(Press::Drag { node, .. }) => match owners.drafts.get(surface, &node) {
|
||||||
|
Some(value) => Activation { node, kind: ActivationKind::Change(value.clone()) },
|
||||||
|
None => return Vec::new(),
|
||||||
|
},
|
||||||
|
Some(Press::Target(pressed)) => {
|
||||||
|
if target(seen.rendered, seen.laid, &seen.tree.index(), at, seen.k()).as_ref() != Some(&pressed) {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
match pressed.control {
|
||||||
|
Control::Button | Control::Scrim => Activation { node: pressed.node, kind: ActivationKind::Press },
|
||||||
|
Control::Toggle => {
|
||||||
|
let shown = current(seen.tree, Some(owners.drafts), &pressed.node, Field::Checked);
|
||||||
|
let checked = matches!(shown.as_deref(), Some(Bound::Bool(true)));
|
||||||
|
Activation { node: pressed.node, kind: ActivationKind::Change(InputValue::Bool(BoolValue { value: !checked })) }
|
||||||
|
}
|
||||||
|
// A Select's chooser and a TextInput's editing are not here: a press on them does nothing, and
|
||||||
|
// does not fall through to a control around them. A Slider's press is a `Drag`, never a target.
|
||||||
|
Control::Slider | Control::Select | Control::TextInput => return Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
owners.commands.activate(activation, seen.tree, owners.drafts, now, owners.ids, owners.port, owners.ledger)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The wheel moves the nearest scroll node at or above what it is over, on the wheel's axis, that
|
||||||
|
/// has room to move that way; at the end of its travel the next scroll ancestor takes it. Under a
|
||||||
|
/// modal only the modal's own subtree is reachable. Offsets are held in device px (Pixels) or cells.
|
||||||
|
fn wheel(at: (f32, f32), delta: (f32, f32), unit: WheelUnit, seen: &Seen<'_>, scroll: &mut ScrollOffsets) {
|
||||||
|
let index = seen.tree.index();
|
||||||
|
let Some(Reach::Node(start) | Reach::Scrim(start)) = reach(seen.rendered, seen.laid, &index, at, seen.k()) else { return };
|
||||||
|
let to_device = seen.k();
|
||||||
|
let line = match seen.metrics {
|
||||||
|
Metrics::Cells => 1.0,
|
||||||
|
Metrics::Pixels => seen.line,
|
||||||
|
};
|
||||||
|
let per = match unit {
|
||||||
|
WheelUnit::Units => to_device,
|
||||||
|
WheelUnit::Lines => line * to_device,
|
||||||
|
};
|
||||||
|
for axis in [0usize, 1] {
|
||||||
|
let amount = [delta.0, delta.1][axis] * per;
|
||||||
|
if !amount.is_finite() || amount == 0.0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut over = Some(start);
|
||||||
|
while let Some(i) = over {
|
||||||
|
let node = &seen.laid.nodes[i];
|
||||||
|
if let Some(max) = node.max_scroll {
|
||||||
|
let held = scroll.of(node);
|
||||||
|
let want = if axis == 0 { (held.0 + amount, held.1) } else { (held.0, held.1 + amount) };
|
||||||
|
let next = clamp(want, max);
|
||||||
|
if next != held {
|
||||||
|
scroll.set(node.id.clone(), next);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
over = node.parent.map(|parent| parent as usize);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
959
crates/thing-core/src/input/tests.rs
Normal file
959
crates/thing-core/src/input/tests.rs
Normal file
|
|
@ -0,0 +1,959 @@
|
||||||
|
//! Pointer input: a press, a drag and a wheel reach the node the user saw drawn, in Pixels (at several
|
||||||
|
//! scales) and in Cells, and end in the one activation primitive, in drafts or in scroll offsets.
|
||||||
|
//! Hit-testing reads the geometry render placed, so every test derives its points from `Placed`
|
||||||
|
//! and never from authored numbers. These tests live in the crate because `Input`, `Seen` and `Owners`
|
||||||
|
//! are not public; for the same reason they cannot use `thing-testkit`'s state port (its types name the
|
||||||
|
//! library build of this crate, not this test build), so `Port`, `Counter` and `Boxes` below are the three
|
||||||
|
//! small doubles they need. The contract documents they press are `tests/support`, shared with the host tests.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use thing_contract::*;
|
||||||
|
use thing_testkit::build::*;
|
||||||
|
|
||||||
|
use super::hit::{Reach, Target, reach, target};
|
||||||
|
use super::pointer::{Owners, Seen};
|
||||||
|
use super::{Drafts, Input, InputEvent, Modifiers, PointerButton, WheelUnit};
|
||||||
|
use crate::bind::{Binder, BoundTree, Instance};
|
||||||
|
use crate::command::Commands;
|
||||||
|
use crate::diagnostic::{Code, Diagnostic};
|
||||||
|
use crate::layout::{Constraint, LaidTree, LayoutFrame, Leaf, Measure, Metrics, Rect, TextLayout, TextRequest, layout};
|
||||||
|
use crate::port::{Address, Change, Entry, IdSource, Interest, Ledger, Lookup, Prefix, Record, StatePort, StateValue, SubscriptionId};
|
||||||
|
use crate::render::{RenderInput, Rendered, ScrollOffsets, Session, render};
|
||||||
|
use crate::resolve::{Limits, resolve};
|
||||||
|
use crate::theme::Theme;
|
||||||
|
use crate::time::Timestamp;
|
||||||
|
|
||||||
|
#[path = "../../tests/support/mod.rs"]
|
||||||
|
mod support;
|
||||||
|
use support::*;
|
||||||
|
|
||||||
|
/// Records by address, the interests asked of the port and the changes queued for a drain.
|
||||||
|
#[derive(Clone, Default)]
|
||||||
|
struct Port {
|
||||||
|
records: HashMap<Address, Entry>,
|
||||||
|
interests: Vec<(SubscriptionId, Interest)>,
|
||||||
|
queue: Vec<Change>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Port {
|
||||||
|
fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn put(&mut self, provider: &ProviderId, document: &SurfaceDocument) {
|
||||||
|
let address = Address { provider: provider.clone(), schema: SchemaId::new(SurfaceDocument::SCHEMA_NAME), key: RecordKey::new(document.record_key()) };
|
||||||
|
self.records.insert(address.clone(), Entry { address, record: Record::Surface(document.clone()) });
|
||||||
|
}
|
||||||
|
|
||||||
|
fn put_item(&mut self, provider: &ProviderId, id: &str, title: &str) {
|
||||||
|
let address = Address { provider: provider.clone(), schema: SchemaId::new("gamecult.thing.test.item.v1"), key: RecordKey::new(id) };
|
||||||
|
let value = StateValue::Record(vec![("Id".into(), StateValue::Text(id.into())), ("Title".into(), StateValue::Text(title.into()))]);
|
||||||
|
let record = Record::State { schema: address.schema.clone(), value };
|
||||||
|
self.records.insert(address.clone(), Entry { address, record });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StatePort for Port {
|
||||||
|
fn read(&self, address: &Address) -> Lookup {
|
||||||
|
self.records.get(address).map_or(Lookup::Absent, |entry| Lookup::Present(entry.clone()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn list(&self, prefix: &Prefix) -> Vec<Lookup> {
|
||||||
|
let mut held: Vec<_> = self.records.values().filter(|entry| prefix.matches(&entry.address)).collect();
|
||||||
|
held.sort_by(|a, b| a.address.key.as_str().cmp(b.address.key.as_str()));
|
||||||
|
held.into_iter().map(|entry| Lookup::Present(entry.clone())).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn subscribe(&mut self, interest: Interest) -> SubscriptionId {
|
||||||
|
let id = SubscriptionId(self.interests.len() as u64);
|
||||||
|
self.interests.push((id, interest));
|
||||||
|
id
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unsubscribe(&mut self, id: SubscriptionId) {
|
||||||
|
self.interests.retain(|(held, _)| *held != id);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drain(&mut self) -> Vec<Change> {
|
||||||
|
std::mem::take(&mut self.queue)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ids that differ by a counter.
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Counter(u128);
|
||||||
|
|
||||||
|
impl IdSource for Counter {
|
||||||
|
fn fill(&mut self, bytes: &mut [u8; 16]) {
|
||||||
|
self.0 += 1;
|
||||||
|
*bytes = self.0.to_be_bytes();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fixed control sizes and no text: these documents hold boxes and controls only.
|
||||||
|
struct Boxes {
|
||||||
|
cells: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Measure for Boxes {
|
||||||
|
fn measure(&mut self, leaf: &Leaf, _: Constraint) -> (f32, f32) {
|
||||||
|
let control = |w: f32, h: f32| if self.cells { (w / 8.0, 1.0) } else { (w, h) };
|
||||||
|
match leaf {
|
||||||
|
Leaf::TextInput { multiline, .. } => control(200.0, if *multiline { 72.0 } else { 24.0 }),
|
||||||
|
Leaf::Toggle { .. } => control(40.0, 20.0),
|
||||||
|
Leaf::Slider { .. } => control(160.0, 20.0),
|
||||||
|
Leaf::Select { .. } => control(160.0, 24.0),
|
||||||
|
Leaf::Text { .. } | Leaf::Image { .. } => (0.0, 0.0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn text(&mut self, _: &TextRequest, _: f32) -> TextLayout {
|
||||||
|
TextLayout { lines: vec![] }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pixels at two scales, and Cells: the modes the pointer must agree with the laid geometry in.
|
||||||
|
const MODES: [(Metrics, f32); 3] = [(Metrics::Pixels, 1.0), (Metrics::Pixels, 1.5), (Metrics::Cells, 1.0)];
|
||||||
|
|
||||||
|
fn viewport(metrics: Metrics) -> (f32, f32) {
|
||||||
|
match metrics {
|
||||||
|
Metrics::Pixels => (400.0, 320.0),
|
||||||
|
Metrics::Cells => (50.0, 20.0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn measure(metrics: Metrics) -> Boxes {
|
||||||
|
Boxes { cells: metrics == Metrics::Cells }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn row_id(item: &str, node: &str) -> NodeId {
|
||||||
|
NodeId::new(format!("{}{node}", Instance::scope_prefix("rows", item, false)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn feed() -> Port {
|
||||||
|
let mut state = Port::new();
|
||||||
|
for n in 0..20 {
|
||||||
|
let id = format!("item-{n:04}");
|
||||||
|
state.put_item(&ProviderId::new(FEED), &id, &id);
|
||||||
|
}
|
||||||
|
state
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- the rig: the stages composed by hand, with the owners input writes through -----
|
||||||
|
|
||||||
|
struct Rig {
|
||||||
|
tree: BoundTree,
|
||||||
|
laid: LaidTree,
|
||||||
|
rendered: Rendered,
|
||||||
|
metrics: Metrics,
|
||||||
|
scale: f32,
|
||||||
|
surface: String,
|
||||||
|
state: Port,
|
||||||
|
ledger: Ledger,
|
||||||
|
input: Input,
|
||||||
|
commands: Commands,
|
||||||
|
drafts: Drafts,
|
||||||
|
scroll: ScrollOffsets,
|
||||||
|
ids: Counter,
|
||||||
|
now: Timestamp,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Rig {
|
||||||
|
fn new(mut state: Port, document: &SurfaceDocument, (metrics, scale): (Metrics, f32)) -> Self {
|
||||||
|
state.put(&document.provider_id, document);
|
||||||
|
let limits = Limits::default();
|
||||||
|
let resolved = resolve(document, &state, &limits).tree.expect("resolves");
|
||||||
|
let mut ledger = Ledger::new();
|
||||||
|
let mut binder = Binder::new(limits);
|
||||||
|
binder.bind(resolved, &mut state, &mut ledger);
|
||||||
|
let tree = binder.tree(&document.record_key()).expect("bound").clone();
|
||||||
|
let mut rig = Self {
|
||||||
|
laid: LaidTree { nodes: vec![], diagnostics: vec![] },
|
||||||
|
rendered: Rendered { commands: vec![], placed: vec![], diagnostics: vec![] },
|
||||||
|
tree,
|
||||||
|
metrics,
|
||||||
|
scale,
|
||||||
|
surface: document.record_key(),
|
||||||
|
state,
|
||||||
|
ledger,
|
||||||
|
input: Input::new(),
|
||||||
|
commands: Commands::new("renderer.test", 15_000),
|
||||||
|
drafts: Drafts::new(),
|
||||||
|
scroll: ScrollOffsets::default(),
|
||||||
|
ids: Counter::default(),
|
||||||
|
now: Timestamp(0),
|
||||||
|
};
|
||||||
|
rig.draw();
|
||||||
|
rig
|
||||||
|
}
|
||||||
|
|
||||||
|
fn frame(&self) -> LayoutFrame {
|
||||||
|
LayoutFrame { viewport: viewport(self.metrics), scale: self.scale, metrics: self.metrics }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The frame the user sees: layout, then render over the scroll offsets, drafts and node states.
|
||||||
|
fn draw(&mut self) {
|
||||||
|
self.laid = layout(&self.tree, &self.frame(), &mut measure(self.metrics)).expect("lays out");
|
||||||
|
let states = self.commands.view(&self.surface);
|
||||||
|
let theme = Theme::std();
|
||||||
|
let input = RenderInput {
|
||||||
|
scale: self.scale,
|
||||||
|
metrics: self.metrics,
|
||||||
|
viewport: viewport(self.metrics),
|
||||||
|
scroll: &self.scroll,
|
||||||
|
theme: &theme,
|
||||||
|
session: Session::new(&self.drafts, &states),
|
||||||
|
};
|
||||||
|
self.rendered = render(&self.tree, &self.laid, &input, &mut measure(self.metrics));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rect(&self, id: &str) -> Rect {
|
||||||
|
self.rendered.placed.iter().find(|placed| placed.id.as_str() == id).unwrap_or_else(|| panic!("no node {id}")).rect
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send(&mut self, event: InputEvent) -> Vec<Diagnostic> {
|
||||||
|
let theme = Theme::std();
|
||||||
|
let seen = Seen { rendered: &self.rendered, laid: &self.laid, tree: &self.tree, metrics: self.metrics, scale: self.scale, line: theme.text["body"].size };
|
||||||
|
let mut owners = Owners {
|
||||||
|
commands: &mut self.commands,
|
||||||
|
drafts: &mut self.drafts,
|
||||||
|
scroll: &mut self.scroll,
|
||||||
|
ids: &mut self.ids,
|
||||||
|
port: &mut self.state,
|
||||||
|
ledger: &mut self.ledger,
|
||||||
|
};
|
||||||
|
self.input.event(&event, &seen, &mut owners, self.now)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn click(&mut self, at: (f32, f32)) -> Vec<Diagnostic> {
|
||||||
|
let mut said = self.send(down(at));
|
||||||
|
said.extend(self.send(up(at)));
|
||||||
|
said
|
||||||
|
}
|
||||||
|
|
||||||
|
fn minted(&mut self) -> Vec<CommandInvocation> {
|
||||||
|
self.commands.take_outbound()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn draft(&self, node: &str) -> Option<InputValue> {
|
||||||
|
self.drafts.get(&self.surface, &nid(node)).cloned()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn offset(&self, node: &str) -> Option<(f32, f32)> {
|
||||||
|
self.scroll.get(&nid(node))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn max_scroll(&self, node: &str) -> (f32, f32) {
|
||||||
|
self.laid.nodes.iter().find(|laid| laid.id.as_str() == node).and_then(|laid| laid.max_scroll).expect("scrolls")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mods() -> Modifiers {
|
||||||
|
Modifiers::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn down(at: (f32, f32)) -> InputEvent {
|
||||||
|
InputEvent::PointerDown { at, button: PointerButton::Primary, modifiers: mods() }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn up(at: (f32, f32)) -> InputEvent {
|
||||||
|
InputEvent::PointerUp { at, button: PointerButton::Primary, modifiers: mods() }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mv(at: (f32, f32)) -> InputEvent {
|
||||||
|
InputEvent::PointerMove { at, modifiers: mods() }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wheel(at: (f32, f32), delta: (f32, f32), unit: WheelUnit) -> InputEvent {
|
||||||
|
InputEvent::Wheel { at, delta, unit, modifiers: mods() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The top-left cell (or, in Pixels, the half-pixel) of a rect: a point that is inside it in every mode.
|
||||||
|
fn inside(rect: Rect) -> (f32, f32) {
|
||||||
|
(rect.x + 0.5, rect.y + 0.5)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn commands_of(invocations: &[CommandInvocation]) -> Vec<&str> {
|
||||||
|
invocations.iter().map(|invocation| invocation.command.as_str()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn index_of(rig: &Rig) -> std::collections::HashMap<&NodeId, &Node> {
|
||||||
|
rig.tree.index()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Device px per logical px, as input holds it.
|
||||||
|
fn device_k(rig: &Rig) -> f32 {
|
||||||
|
match rig.metrics {
|
||||||
|
Metrics::Pixels => rig.scale,
|
||||||
|
Metrics::Cells => 1.0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The node, or the modal whose scrim it is, that a point reaches.
|
||||||
|
fn hit_node(rig: &Rig, at: (f32, f32)) -> Option<String> {
|
||||||
|
match reach(&rig.rendered, &rig.laid, &index_of(rig), at, device_k(rig))? {
|
||||||
|
Reach::Node(i) | Reach::Scrim(i) => Some(rig.laid.nodes[i].id.as_str().to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rig_target(rig: &Rig, at: (f32, f32)) -> Option<Target> {
|
||||||
|
target(&rig.rendered, &rig.laid, &index_of(rig), at, device_k(rig))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- hit-testing agrees with the laid geometry -----
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_point_inside_the_absolute_target_hits_target_and_one_on_the_board_only_hits_board() {
|
||||||
|
for mode in MODES {
|
||||||
|
let rig = Rig::new(Port::new(), &target_surface(), mode);
|
||||||
|
let (target, board) = (rig.rect("target"), rig.rect("board"));
|
||||||
|
// The far corner of the target.
|
||||||
|
let corner = (target.x + target.w - 0.5, target.y + target.h - 0.5);
|
||||||
|
assert_eq!(hit_node(&rig, corner).as_deref(), Some("target"), "{mode:?}");
|
||||||
|
assert_eq!(hit_node(&rig, inside(board)).as_deref(), Some("board"), "{mode:?}");
|
||||||
|
assert!(target.x > board.x && target.y > board.y, "{mode:?}: the target stands inside the board, away from its corner");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_rect_is_half_open_so_a_shared_edge_belongs_to_the_second_node() {
|
||||||
|
for mode in MODES {
|
||||||
|
let rig = Rig::new(Port::new(), &surface(column("root", None, Overflow::Visible, vec![button("a", "x", 160.0, 48.0), button("b", "x", 160.0, 48.0)]), vec![decl("x", &[])]), mode);
|
||||||
|
let (a, b) = (rig.rect("a"), rig.rect("b"));
|
||||||
|
assert_eq!(a.y + a.h, b.y, "{mode:?}: the buttons touch");
|
||||||
|
let edge = (a.x + 0.5, b.y);
|
||||||
|
assert!(rig_target(&rig, edge).is_some_and(|hit| hit.node.as_str() == "b"), "{mode:?}");
|
||||||
|
let last = (a.x + 0.5, b.y - 0.25);
|
||||||
|
assert!(rig_target(&rig, last).is_some_and(|hit| hit.node.as_str() == "a"), "{mode:?}");
|
||||||
|
let under = (b.x + 0.5, b.y + b.h);
|
||||||
|
assert_eq!(rig_target(&rig, under), None, "{mode:?}: the bottom edge is outside");
|
||||||
|
let beyond = (a.x + a.w, a.y + 0.5);
|
||||||
|
assert_ne!(rig_target(&rig, beyond).map(|hit| hit.node), Some(nid("a")), "{mode:?}: the right edge is outside");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_visible_node_is_reached_inside_its_own_visible_rect() {
|
||||||
|
let documents = [
|
||||||
|
(modal_surface(), Port::new()),
|
||||||
|
(rows_surface(), feed()),
|
||||||
|
(controls_surface(), Port::new()),
|
||||||
|
(nested_surface(), Port::new()),
|
||||||
|
(clip_surface(), Port::new()),
|
||||||
|
(nonmodal_surface(Anchor::Viewport), Port::new()),
|
||||||
|
(target_surface(), Port::new()),
|
||||||
|
];
|
||||||
|
for mode in MODES {
|
||||||
|
for (document, state) in &documents {
|
||||||
|
let rig = Rig::new(state.clone(), document, mode);
|
||||||
|
for placed in &rig.rendered.placed {
|
||||||
|
let Some(seen) = placed.visible.filter(|r| r.w >= 1.0 && r.h >= 1.0) else { continue };
|
||||||
|
let at = inside(seen);
|
||||||
|
let hit = hit_node(&rig, at).expect("something is there");
|
||||||
|
let reached = rig.rendered.placed.iter().find(|p| p.id.as_str() == hit).unwrap();
|
||||||
|
let within = reached.visible.is_some_and(|r| at.0 >= r.x && at.0 < r.x + r.w && at.1 >= r.y && at.1 < r.y + r.h);
|
||||||
|
assert!(within, "{mode:?} {}: {hit} reached at {at:?} is not drawn there", document.label.as_str());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_node_outside_its_clip_is_not_hit_where_its_rect_reaches_past_the_clip() {
|
||||||
|
for mode in MODES {
|
||||||
|
let rig = Rig::new(Port::new(), &clip_surface(), mode);
|
||||||
|
let (frame, tall) = (rig.rect("frame"), rig.rect("tall"));
|
||||||
|
assert!(tall.y + tall.h > frame.y + frame.h, "{mode:?}: the button runs past the clip");
|
||||||
|
let below = (tall.x + 0.5, frame.y + frame.h + 0.5);
|
||||||
|
assert!(below.1 < tall.y + tall.h);
|
||||||
|
assert_eq!(rig_target(&rig, below), None, "{mode:?}");
|
||||||
|
assert_ne!(hit_node(&rig, below).as_deref(), Some("tall"), "{mode:?}");
|
||||||
|
// Inside the clip it is hit.
|
||||||
|
let inside_clip = rig_target(&rig, inside(frame));
|
||||||
|
assert_eq!(inside_clip.map(|hit| hit.node.as_str().to_string()).as_deref(), Some("tall"), "{mode:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- the edge of a node, at a scale that does not divide -----
|
||||||
|
|
||||||
|
/// Rows of odd widths and heights, so edges fall between whole logical px at a fractional scale.
|
||||||
|
fn seam_surface() -> SurfaceDocument {
|
||||||
|
let row = |id: &str, h: f64, widths: &[f64]| {
|
||||||
|
let mut row = column(id, None, Overflow::Visible, widths.iter().enumerate().map(|(i, w)| fixed(&format!("{id}-{i}"), *w, h)).collect());
|
||||||
|
if let Node::Box(b) = &mut row {
|
||||||
|
b.style.direction = Direction::Row;
|
||||||
|
b.style.size = size2(Dimension::Percent(Scalar { value: 100.0 }), px(h));
|
||||||
|
b.style.justify_content = ContentAlign::Start;
|
||||||
|
}
|
||||||
|
row
|
||||||
|
};
|
||||||
|
surface(
|
||||||
|
column("root", None, Overflow::Visible, vec![
|
||||||
|
row("r0", 7.0, &[9.0, 14.0, 5.0, 31.0]),
|
||||||
|
row("r1", 13.0, &[11.0, 3.0, 17.0]),
|
||||||
|
row("r2", 5.0, &[6.0, 6.0, 6.0, 6.0, 7.0]),
|
||||||
|
row("r3", 19.0, &[23.0, 29.0, 13.0]),
|
||||||
|
]),
|
||||||
|
vec![],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_first_device_pixel_past_a_nodes_right_or_bottom_edge_is_not_the_node_at_every_scale() {
|
||||||
|
let scales = [1.0, 1.25, 1.5, 1.75, 2.0, 2.5, 3.0];
|
||||||
|
for mode in scales.map(|scale| (Metrics::Pixels, scale)) {
|
||||||
|
let rig = Rig::new(Port::new(), &seam_surface(), mode);
|
||||||
|
let k = device_k(&rig);
|
||||||
|
let mut leaves = 0;
|
||||||
|
for node in rig.laid.nodes.iter().filter(|node| node.id.as_str().contains('-')) {
|
||||||
|
leaves += 1;
|
||||||
|
let (id, r) = (node.id.as_str(), node.rect);
|
||||||
|
assert!(r.w >= 1.0 && r.h >= 1.0 && r.x.fract() == 0.0 && r.y.fract() == 0.0, "{mode:?} {id}: laid in whole device px, {r:?}");
|
||||||
|
// Device pixels, as a host at this scale reports a pointer: the pixel's corner and its centre.
|
||||||
|
let at = |dx: f32, dy: f32, off: f32| ((dx + off) / k, (dy + off) / k);
|
||||||
|
for off in [0.0, 0.5] {
|
||||||
|
let last = at(r.x + r.w - 1.0, r.y + r.h - 1.0, off);
|
||||||
|
assert_eq!(hit_node(&rig, last).as_deref(), Some(id), "{mode:?} {id} the last pixel of the node, +{off}");
|
||||||
|
let right = at(r.x + r.w, r.y, off);
|
||||||
|
assert_ne!(hit_node(&rig, right).as_deref(), Some(id), "{mode:?} {id} the pixel right of the node, +{off}");
|
||||||
|
let below = at(r.x, r.y + r.h, off);
|
||||||
|
assert_ne!(hit_node(&rig, below).as_deref(), Some(id), "{mode:?} {id} the pixel below the node, +{off}");
|
||||||
|
let first = at(r.x, r.y, off);
|
||||||
|
assert_eq!(hit_node(&rig, first).as_deref(), Some(id), "{mode:?} {id} the first pixel of the node, +{off}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(leaves, 15, "{mode:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- a non-modal overlay -----
|
||||||
|
|
||||||
|
fn nonmodal_surface(anchor: Anchor) -> SurfaceDocument {
|
||||||
|
let pop = Node::Overlay(OverlayNode { common: common("pop"), anchor, modal: false, dismiss: command("dismiss"), children: vec![button("pop-button", "inside", 80.0, 48.0)] });
|
||||||
|
surface(
|
||||||
|
column("root", None, Overflow::Visible, vec![button("behind", "behind", 320.0, 48.0), button("other", "other", 320.0, 48.0), pop]),
|
||||||
|
vec![decl("behind", &[]), decl("other", &[]), decl("inside", &[]), decl("dismiss", &[])],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_press_passes_through_a_non_modal_overlays_root_to_what_lies_beneath_and_its_own_content_still_takes_it() {
|
||||||
|
let node = Anchor::Node(AnchorNode { node: nid("behind") });
|
||||||
|
for mode in MODES {
|
||||||
|
for anchor in [Anchor::Viewport, node.clone()] {
|
||||||
|
let mut rig = Rig::new(Port::new(), &nonmodal_surface(anchor.clone()), mode);
|
||||||
|
let (behind, other, inner) = (rig.rect("behind"), rig.rect("other"), rig.rect("pop-button"));
|
||||||
|
let (a, b) = ((behind.x + behind.w - 0.5, behind.y + 0.5), (other.x + other.w - 0.5, other.y + 0.5));
|
||||||
|
for at in [a, b] {
|
||||||
|
assert!(!(at.0 >= inner.x && at.0 < inner.x + inner.w && at.1 >= inner.y && at.1 < inner.y + inner.h), "{mode:?} {anchor:?}: {at:?} is clear of the overlay's content");
|
||||||
|
assert_eq!(hit_node(&rig, at).as_deref().map(|id| id != "pop"), Some(true), "{mode:?} {anchor:?}: the overlay's root is not what is hit at {at:?}");
|
||||||
|
}
|
||||||
|
rig.click(a);
|
||||||
|
assert_eq!(commands_of(&rig.minted()), ["behind"], "{mode:?} {anchor:?}: the press reaches the anchor or the node under the viewport overlay");
|
||||||
|
rig.click(b);
|
||||||
|
assert_eq!(commands_of(&rig.minted()), ["other"], "{mode:?} {anchor:?}");
|
||||||
|
// The overlay's own content is drawn over them and takes its press.
|
||||||
|
rig.click(inside(inner));
|
||||||
|
assert_eq!(commands_of(&rig.minted()), ["inside"], "{mode:?} {anchor:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_wheel_over_a_non_modal_overlays_root_reaches_the_pane_beneath() {
|
||||||
|
let pane = column("pane", Some((160.0, 80.0)), Overflow::Scroll, vec![fixed("fill", 160.0, 400.0)]);
|
||||||
|
let document = surface(column("root", None, Overflow::Visible, vec![pane, overlay("pop", false, vec![fixed("pop-body", 8.0, 16.0)])]), vec![decl("dismiss", &[])]);
|
||||||
|
for mode in MODES {
|
||||||
|
let mut rig = Rig::new(Port::new(), &document, mode);
|
||||||
|
let pane = rig.rect("pane");
|
||||||
|
rig.send(wheel((pane.x + pane.w - 0.5, pane.y + pane.h - 0.5), (0.0, 16.0), WheelUnit::Units));
|
||||||
|
assert!(rig.offset("pane").is_some_and(|o| o.1 > 0.0), "{mode:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- the modal -----
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_modal_confirms_inside_the_dialog_and_dismisses_outside_it_and_never_reaches_beneath() {
|
||||||
|
for mode in MODES {
|
||||||
|
let mut rig = Rig::new(Port::new(), &modal_surface(), mode);
|
||||||
|
// Inside the dialog: the confirm button.
|
||||||
|
rig.click(inside(rig.rect("confirm")));
|
||||||
|
assert_eq!(commands_of(&rig.minted()), ["confirm"], "{mode:?}");
|
||||||
|
// Over a main-tree button under the scrim: the scrim's dismissal, once, and not the button's command.
|
||||||
|
let behind = rig.rect("behind");
|
||||||
|
rig.click((behind.x + behind.w - 0.5, behind.y + 0.5));
|
||||||
|
assert_eq!(commands_of(&rig.minted()), ["dismiss"], "{mode:?}");
|
||||||
|
// The dialog's own body is not the scrim: nothing.
|
||||||
|
let dialog = rig.rect("dialog");
|
||||||
|
rig.click((dialog.x + dialog.w - 0.5, dialog.y + dialog.h - 0.5));
|
||||||
|
assert_eq!(rig.minted(), vec![], "{mode:?}");
|
||||||
|
// The scrim is the whole viewport: a corner far from everything dismisses.
|
||||||
|
let (w, h) = viewport(mode.0);
|
||||||
|
let far = match mode.0 {
|
||||||
|
Metrics::Pixels => (w - 1.0, h - 1.0),
|
||||||
|
Metrics::Cells => (w - 0.5, h - 0.5),
|
||||||
|
};
|
||||||
|
assert_eq!(hit_node(&rig, far).as_deref(), Some("modal"), "{mode:?}");
|
||||||
|
// (The overlay that dismissed above still waits on its result, so it is silent: a fresh surface.)
|
||||||
|
let mut fresh = Rig::new(Port::new(), &modal_surface(), mode);
|
||||||
|
fresh.click(far);
|
||||||
|
assert_eq!(commands_of(&fresh.minted()), ["dismiss"], "{mode:?}");
|
||||||
|
// And the same press again, while the first waits, mints nothing more.
|
||||||
|
fresh.click(far);
|
||||||
|
assert_eq!(fresh.minted(), vec![], "{mode:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_press_on_the_scrim_released_on_a_button_activates_nothing() {
|
||||||
|
let mut rig = Rig::new(Port::new(), &modal_surface(), MODES[0]);
|
||||||
|
let behind = rig.rect("behind");
|
||||||
|
let (scrim, confirm) = ((behind.x + behind.w - 0.5, behind.y + 0.5), inside(rig.rect("confirm")));
|
||||||
|
rig.send(down(scrim));
|
||||||
|
rig.send(up(confirm));
|
||||||
|
assert_eq!(rig.minted(), vec![]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- scroll -----
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_click_hits_the_row_drawn_there_after_a_scroll_and_not_a_row_scrolled_out() {
|
||||||
|
for mode in MODES {
|
||||||
|
let mut rig = Rig::new(feed(), &rows_surface(), mode);
|
||||||
|
let (first, second) = (row_id("item-0000", "row"), row_id("item-0001", "row"));
|
||||||
|
let (r0, r1) = (rig.rect(first.as_str()), rig.rect(second.as_str()));
|
||||||
|
let step = r1.y - r0.y;
|
||||||
|
assert!(step > 0.0);
|
||||||
|
// At rest the click at row 0's corner is row 0, whose invocation names it in `items`.
|
||||||
|
rig.click(inside(r0));
|
||||||
|
let minted = rig.minted();
|
||||||
|
assert_eq!((minted[0].source.as_str(), minted[0].items.clone()), ("row", vec!["item-0000".to_string()]), "{mode:?}");
|
||||||
|
// Scrolled by one row (offsets are device px in Pixels): row 1 is drawn where row 0 was.
|
||||||
|
let k = if mode.0 == Metrics::Pixels { mode.1 } else { 1.0 };
|
||||||
|
rig.scroll.set(nid("pane"), (0.0, step * k));
|
||||||
|
rig.draw();
|
||||||
|
assert_eq!(rig.rect(second.as_str()).y, r0.y, "{mode:?}");
|
||||||
|
rig.click(inside(r0));
|
||||||
|
assert_eq!(rig.minted()[0].items, vec!["item-0001".to_string()], "{mode:?}");
|
||||||
|
// Row 0 is above the pane's clip now: its rect is not hit anywhere, though a point there is drawn.
|
||||||
|
let gone = rig.rendered.placed.iter().find(|p| p.id == first).unwrap();
|
||||||
|
let pane = rig.rect("pane");
|
||||||
|
let over = (pane.x + 0.5, gone.rect.y + 0.5);
|
||||||
|
assert!(over.1 < pane.y, "{mode:?}: the scrolled-out row is above the pane");
|
||||||
|
assert_ne!(hit_node(&rig, over).as_deref(), Some(first.as_str()), "{mode:?}");
|
||||||
|
assert_eq!(rig_target(&rig, over), None, "{mode:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_wheel_moves_the_pane_and_clamps_at_the_end_then_goes_to_the_next_pane() {
|
||||||
|
for mode in MODES {
|
||||||
|
let mut rig = Rig::new(Port::new(), &nested_surface(), mode);
|
||||||
|
let k = if mode.0 == Metrics::Pixels { mode.1 } else { 1.0 };
|
||||||
|
let (inner, outer) = (rig.rect("inner"), rig.rect("outer"));
|
||||||
|
let over = inside(inner);
|
||||||
|
let (inner_max, _) = (rig.max_scroll("inner"), 0);
|
||||||
|
assert!(inner_max.1 > 0.0 && rig.max_scroll("outer").1 > 0.0, "{mode:?}");
|
||||||
|
// Far past the end: the inner pane clamps at its travel, the outer stays.
|
||||||
|
rig.send(wheel(over, (0.0, 100_000.0), WheelUnit::Units));
|
||||||
|
assert_eq!((rig.offset("inner"), rig.offset("outer")), (Some((0.0, inner_max.1)), None), "{mode:?}");
|
||||||
|
// At the end of travel the same wheel goes to the pane around it.
|
||||||
|
rig.send(wheel(over, (0.0, 16.0), WheelUnit::Units));
|
||||||
|
assert_eq!((rig.offset("inner"), rig.offset("outer")), (Some((0.0, inner_max.1)), Some((0.0, 16.0 * k))), "{mode:?}");
|
||||||
|
// The other way the inner pane has room, so it takes it and the outer holds.
|
||||||
|
rig.send(wheel(over, (0.0, -8.0), WheelUnit::Units));
|
||||||
|
assert_eq!(rig.offset("inner"), Some((0.0, inner_max.1 - 8.0 * k)), "{mode:?}");
|
||||||
|
assert_eq!(rig.offset("outer"), Some((0.0, 16.0 * k)), "{mode:?}");
|
||||||
|
// Back to the start, then further: clamps at zero and the outer takes the rest of the way back.
|
||||||
|
rig.send(wheel(over, (0.0, -100_000.0), WheelUnit::Units));
|
||||||
|
assert_eq!(rig.offset("inner"), Some((0.0, 0.0)), "{mode:?}");
|
||||||
|
rig.send(wheel(over, (0.0, -4.0), WheelUnit::Units));
|
||||||
|
assert_eq!(rig.offset("outer"), Some((0.0, 12.0 * k)), "{mode:?}");
|
||||||
|
// A wheel off every pane moves nothing; the horizontal axis has no travel here.
|
||||||
|
let before = (rig.offset("inner"), rig.offset("outer"));
|
||||||
|
rig.send(wheel((outer.x - 0.5, outer.y - 0.5), (0.0, 10.0), WheelUnit::Units));
|
||||||
|
rig.send(wheel(over, (10.0, 0.0), WheelUnit::Units));
|
||||||
|
assert_eq!((rig.offset("inner"), rig.offset("outer")), before, "{mode:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_wheel_line_is_one_cell_in_cells_and_the_body_text_size_in_pixels() {
|
||||||
|
let mut cells = Rig::new(Port::new(), &nested_surface(), (Metrics::Cells, 1.0));
|
||||||
|
cells.send(wheel(inside(cells.rect("inner")), (0.0, 3.0), WheelUnit::Lines));
|
||||||
|
assert_eq!(cells.offset("inner"), Some((0.0, 3.0)));
|
||||||
|
for scale in [1.0, 1.5] {
|
||||||
|
let mut pixels = Rig::new(Port::new(), &nested_surface(), (Metrics::Pixels, scale));
|
||||||
|
pixels.send(wheel(inside(pixels.rect("inner")), (0.0, 2.0), WheelUnit::Lines));
|
||||||
|
assert_eq!(pixels.offset("inner"), Some((0.0, 2.0 * 16.0 * scale)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_wheel_over_a_modal_never_scrolls_the_tree_beneath() {
|
||||||
|
let pane = column("pane", Some((160.0, 80.0)), Overflow::Scroll, vec![fixed("fill", 160.0, 400.0)]);
|
||||||
|
let document = surface(column("root", None, Overflow::Visible, vec![pane, overlay("modal", true, vec![fixed("dialog", 80.0, 48.0)])]), vec![decl("dismiss", &[])]);
|
||||||
|
for mode in MODES {
|
||||||
|
let mut rig = Rig::new(Port::new(), &document, mode);
|
||||||
|
rig.send(wheel(inside(rig.rect("pane")), (0.0, 16.0), WheelUnit::Units));
|
||||||
|
assert_eq!(rig.offset("pane"), None, "{mode:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- press semantics -----
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_press_released_elsewhere_or_with_another_button_or_after_a_cancel_activates_nothing() {
|
||||||
|
for mode in MODES {
|
||||||
|
let mut rig = Rig::new(Port::new(), &controls_surface(), mode);
|
||||||
|
let (a, b) = (inside(rig.rect("a")), inside(rig.rect("b")));
|
||||||
|
// Down on a, up on b.
|
||||||
|
rig.send(down(a));
|
||||||
|
rig.send(up(b));
|
||||||
|
// Secondary and middle buttons never press.
|
||||||
|
for button in [PointerButton::Secondary, PointerButton::Middle] {
|
||||||
|
rig.send(InputEvent::PointerDown { at: a, button, modifiers: mods() });
|
||||||
|
rig.send(InputEvent::PointerUp { at: a, button, modifiers: mods() });
|
||||||
|
}
|
||||||
|
// Down, the platform takes the pointer, a stray up.
|
||||||
|
rig.send(down(a));
|
||||||
|
rig.send(InputEvent::PointerCancel);
|
||||||
|
rig.send(up(a));
|
||||||
|
// An up with no press.
|
||||||
|
rig.send(up(a));
|
||||||
|
assert_eq!(rig.minted(), vec![], "{mode:?}");
|
||||||
|
// And the same button down and up mints once.
|
||||||
|
rig.click(a);
|
||||||
|
assert_eq!(commands_of(&rig.minted()), ["go"], "{mode:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_secondary_up_does_not_release_a_primary_press() {
|
||||||
|
let mut rig = Rig::new(Port::new(), &controls_surface(), MODES[0]);
|
||||||
|
let a = inside(rig.rect("a"));
|
||||||
|
rig.send(down(a));
|
||||||
|
rig.send(InputEvent::PointerUp { at: a, button: PointerButton::Secondary, modifiers: mods() });
|
||||||
|
assert_eq!(rig.minted(), vec![]);
|
||||||
|
rig.send(up(a));
|
||||||
|
assert_eq!(commands_of(&rig.minted()), ["go"]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_busy_button_mints_once_however_often_it_is_pressed() {
|
||||||
|
for mode in MODES {
|
||||||
|
let mut rig = Rig::new(Port::new(), &controls_surface(), mode);
|
||||||
|
let a = inside(rig.rect("a"));
|
||||||
|
assert_eq!(rig.click(a), vec![]);
|
||||||
|
assert_eq!(rig.click(a), vec![], "{mode:?}: a busy press is silent, not a refusal");
|
||||||
|
assert_eq!(commands_of(&rig.minted()), ["go"], "{mode:?}");
|
||||||
|
// The user sees it: the busy button is drawn disabled.
|
||||||
|
rig.draw();
|
||||||
|
let disabled = Theme::std().colors["thing.control.disabled"].clone();
|
||||||
|
assert!(rig.rendered.commands.iter().any(|c| matches!(c, crate::render::RenderCommand::FillRect { color, .. } if *color == disabled)), "{mode:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_toggle_flips_its_draft_and_fires_on_change_once_per_press() {
|
||||||
|
for mode in MODES {
|
||||||
|
let mut rig = Rig::new(Port::new(), &controls_surface(), mode);
|
||||||
|
let flag = inside(rig.rect("flag"));
|
||||||
|
rig.click(flag);
|
||||||
|
let first = rig.minted();
|
||||||
|
assert_eq!(commands_of(&first), ["flip"], "{mode:?}");
|
||||||
|
assert_eq!(first[0].captured[0].value, InputValue::Bool(BoolValue { value: true }), "{mode:?}");
|
||||||
|
assert_eq!(rig.draft("flag"), Some(InputValue::Bool(BoolValue { value: true })));
|
||||||
|
// A second press is a change to a control with an invocation waiting: it is refused and says so, it
|
||||||
|
// fires nothing more, and it leaves the draft that was sent (a busy control holds no unsent value).
|
||||||
|
let said = rig.click(flag);
|
||||||
|
assert_eq!(said.iter().map(|d| (d.code, d.node.as_ref().map(NodeId::as_str))).collect::<Vec<_>>(), vec![(Code::ActivationRefused, Some("flag"))], "{mode:?}");
|
||||||
|
assert_eq!(rig.minted(), vec![], "{mode:?}");
|
||||||
|
assert_eq!(rig.draft("flag"), Some(InputValue::Bool(BoolValue { value: true })), "{mode:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_slider_drag_writes_snapped_drafts_and_commits_once_wherever_it_is_released() {
|
||||||
|
for mode in MODES {
|
||||||
|
let mut rig = Rig::new(Port::new(), &controls_surface(), mode);
|
||||||
|
let track = rig.rect("level");
|
||||||
|
let along = |fraction: f32| (track.x + fraction * track.w, track.y + 0.5);
|
||||||
|
let value = |v: f64| Some(InputValue::Number(NumberValue { value: v }));
|
||||||
|
rig.send(down(along(0.34)));
|
||||||
|
assert_eq!(rig.draft("level"), value(30.0), "{mode:?}: 34 snaps to the step from min");
|
||||||
|
rig.send(mv(along(0.76)));
|
||||||
|
assert_eq!(rig.draft("level"), value(80.0), "{mode:?}");
|
||||||
|
// The drag is shown while it is made.
|
||||||
|
rig.draw();
|
||||||
|
let thumb = |rig: &Rig| rig.rendered.commands.iter().filter_map(|c| match c {
|
||||||
|
crate::render::RenderCommand::FillRect { rect, .. } if rect.w <= track.h.max(1.0) + 0.01 && rect.h > 0.0 => Some(rect.x),
|
||||||
|
_ => None,
|
||||||
|
}).last();
|
||||||
|
assert!(thumb(&rig).is_some());
|
||||||
|
// Released far outside the track, even outside the pane: one commit of the last draft.
|
||||||
|
rig.send(mv((track.x + track.w * 3.0, track.y + 500.0)));
|
||||||
|
assert_eq!(rig.draft("level"), value(100.0), "{mode:?}: past the end clamps");
|
||||||
|
rig.send(up((track.x - 900.0, track.y - 900.0)));
|
||||||
|
let minted = rig.minted();
|
||||||
|
assert_eq!(commands_of(&minted), ["set"], "{mode:?}");
|
||||||
|
assert_eq!(minted[0].captured[0].value, InputValue::Number(NumberValue { value: 100.0 }), "{mode:?}");
|
||||||
|
// Moving after the up changes nothing.
|
||||||
|
rig.send(mv(along(0.1)));
|
||||||
|
assert_eq!(rig.draft("level"), value(100.0), "{mode:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_cancelled_slider_press_leaves_the_draft_it_found_and_fires_nothing() {
|
||||||
|
for mode in MODES {
|
||||||
|
let mut rig = Rig::new(Port::new(), &controls_surface(), mode);
|
||||||
|
let track = rig.rect("level");
|
||||||
|
let along = |fraction: f32| (track.x + fraction * track.w, track.y + 0.5);
|
||||||
|
// No draft before: a press then a cancel leaves none, and a stray up commits nothing.
|
||||||
|
rig.send(down(along(0.5)));
|
||||||
|
assert!(rig.draft("level").is_some());
|
||||||
|
rig.send(InputEvent::PointerCancel);
|
||||||
|
rig.send(up(along(0.5)));
|
||||||
|
assert_eq!((rig.draft("level"), rig.minted()), (None, vec![]), "{mode:?}");
|
||||||
|
// A draft that is already waiting on a result comes back as it was.
|
||||||
|
rig.send(down(along(0.3)));
|
||||||
|
rig.send(up(along(0.3)));
|
||||||
|
assert_eq!(commands_of(&rig.minted()), ["set"]);
|
||||||
|
let held = rig.draft("level");
|
||||||
|
rig.send(down(along(0.9)));
|
||||||
|
rig.send(mv(along(0.2)));
|
||||||
|
rig.send(InputEvent::PointerCancel);
|
||||||
|
assert_eq!((rig.draft("level"), rig.minted()), (held, vec![]), "{mode:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_press_on_a_select_or_a_text_input_does_nothing_yet() {
|
||||||
|
for mode in MODES {
|
||||||
|
let mut rig = Rig::new(Port::new(), &fields_surface(), mode);
|
||||||
|
for id in ["field", "choice"] {
|
||||||
|
assert_eq!(rig.click(inside(rig.rect(id))), vec![], "{mode:?} {id}");
|
||||||
|
}
|
||||||
|
assert_eq!((rig.minted(), rig.drafts.is_empty()), (vec![], true), "{mode:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_click_while_a_command_waits_for_confirmation_is_a_refusal_the_event_returns() {
|
||||||
|
for mode in MODES {
|
||||||
|
let mut document = surface(column("root", None, Overflow::Visible, vec![button("a", "ask", 160.0, 48.0), button("b", "go", 160.0, 48.0)]), vec![decl("ask", &[]), decl("go", &[])]);
|
||||||
|
document.commands[0].confirm = Some("Sure?".into());
|
||||||
|
let mut rig = Rig::new(Port::new(), &document, mode);
|
||||||
|
assert_eq!(rig.click(inside(rig.rect("a"))), vec![]);
|
||||||
|
assert!(rig.commands.confirming().is_some() && rig.minted().is_empty(), "{mode:?}");
|
||||||
|
let said = rig.click(inside(rig.rect("b")));
|
||||||
|
assert_eq!(said.iter().map(|d| d.code).collect::<Vec<_>>(), vec![Code::ActivationRefused], "{mode:?}");
|
||||||
|
assert_eq!(said[0].node.as_ref().map(NodeId::as_str), Some("b"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----- a control that takes no change holds no unsent value -----
|
||||||
|
|
||||||
|
fn result_change(sent: &CommandInvocation, clear: bool) -> Change {
|
||||||
|
let result = CommandResult::completed(sent, seq(1), None, clear, None);
|
||||||
|
let address = Address { provider: ProviderId::new(PROVIDER), schema: SchemaId::new(CommandResult::SCHEMA_NAME), key: RecordKey::new(result.record_key()) };
|
||||||
|
Change::Upsert(Entry { address, record: Record::Result(result) })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn refusals(said: &[Diagnostic]) -> Vec<(Code, Option<&str>)> {
|
||||||
|
said.iter().map(|d| (d.code, d.node.as_ref().map(NodeId::as_str))).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_slider_that_waits_for_its_result_takes_no_press_or_drag_and_a_completion_leaves_no_stray_draft() {
|
||||||
|
for mode in MODES {
|
||||||
|
let mut rig = Rig::new(Port::new(), &controls_surface(), mode);
|
||||||
|
let track = rig.rect("level");
|
||||||
|
let along = |fraction: f32| (track.x + fraction * track.w, track.y + 0.5);
|
||||||
|
let value = |v: f64| Some(InputValue::Number(NumberValue { value: v }));
|
||||||
|
rig.send(down(along(0.3)));
|
||||||
|
rig.send(up(along(0.3)));
|
||||||
|
let sent = rig.minted().remove(0);
|
||||||
|
assert_eq!(rig.draft("level"), value(30.0), "{mode:?}");
|
||||||
|
// The slider waits: a second press and its drag are refused, say so, and write nothing.
|
||||||
|
assert_eq!(refusals(&rig.send(down(along(0.8)))), vec![(Code::ActivationRefused, Some("level"))], "{mode:?}");
|
||||||
|
assert_eq!(rig.draft("level"), value(30.0), "{mode:?}: the press wrote nothing");
|
||||||
|
rig.send(mv(along(0.9)));
|
||||||
|
assert_eq!(rig.draft("level"), value(30.0), "{mode:?}: a refused press starts no drag");
|
||||||
|
assert_eq!(rig.send(up(along(0.9))), vec![], "{mode:?}");
|
||||||
|
assert_eq!(rig.minted(), vec![], "{mode:?}");
|
||||||
|
// The result clears the draft that was sent, and nothing else is left drawn on the slider.
|
||||||
|
let tree = &rig.tree;
|
||||||
|
rig.commands.apply(&result_change(&sent, true), Timestamp(5), &|_| Some(tree), &mut rig.drafts, &mut rig.state, &mut rig.ledger);
|
||||||
|
assert_eq!(rig.draft("level"), None, "{mode:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_toggle_pressed_while_it_waits_is_refused_and_a_completion_leaves_the_provider_true() {
|
||||||
|
for mode in MODES {
|
||||||
|
let mut rig = Rig::new(Port::new(), &controls_surface(), mode);
|
||||||
|
let flag = inside(rig.rect("flag"));
|
||||||
|
rig.click(flag);
|
||||||
|
let sent = rig.minted().remove(0);
|
||||||
|
assert_eq!(refusals(&rig.click(flag)), vec![(Code::ActivationRefused, Some("flag"))], "{mode:?}");
|
||||||
|
let tree = &rig.tree;
|
||||||
|
rig.commands.apply(&result_change(&sent, true), Timestamp(5), &|_| Some(tree), &mut rig.drafts, &mut rig.state, &mut rig.ledger);
|
||||||
|
assert_eq!(rig.draft("flag"), None, "{mode:?}: nothing survives to show a checked box the provider does not hold");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_slider_press_while_a_command_waits_for_confirmation_writes_no_draft() {
|
||||||
|
for mode in MODES {
|
||||||
|
let mut document = controls_surface();
|
||||||
|
document.commands.iter_mut().find(|c| c.id.as_str() == "go").unwrap().confirm = Some("Sure?".into());
|
||||||
|
let mut rig = Rig::new(Port::new(), &document, mode);
|
||||||
|
rig.click(inside(rig.rect("a")));
|
||||||
|
assert!(rig.commands.confirming().is_some(), "{mode:?}");
|
||||||
|
let track = rig.rect("level");
|
||||||
|
let said = rig.send(down((track.x + 0.5 * track.w, track.y + 0.5)));
|
||||||
|
assert_eq!(refusals(&said), vec![(Code::ActivationRefused, Some("level"))], "{mode:?}");
|
||||||
|
assert_eq!((rig.draft("level"), rig.drafts.is_empty()), (None, true), "{mode:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn input_other_than_the_pointer_changes_nothing() {
|
||||||
|
let mut rig = Rig::new(Port::new(), &controls_surface(), MODES[0]);
|
||||||
|
let before = (rig.rendered.clone(), rig.drafts.len());
|
||||||
|
for event in [
|
||||||
|
InputEvent::Key { key: crate::input::Key::Enter, modifiers: mods(), repeat: false },
|
||||||
|
InputEvent::Text("x".into()),
|
||||||
|
InputEvent::Compose { text: "か".into(), cursor: None },
|
||||||
|
InputEvent::Focus(true),
|
||||||
|
] {
|
||||||
|
assert_eq!(rig.send(event), vec![]);
|
||||||
|
}
|
||||||
|
assert_eq!((rig.minted(), rig.drafts.len()), (vec![], before.1));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_slider_snaps_from_its_own_minimum_and_follows_its_own_track() {
|
||||||
|
for mode in MODES {
|
||||||
|
let mut rig = Rig::new(Port::new(), &lone_slider(20.0, 120.0, 10.0), mode);
|
||||||
|
let track = rig.rect("level");
|
||||||
|
assert!(track.x > 0.0, "{mode:?}: the track does not start at the root's edge");
|
||||||
|
let along = |fraction: f32| (track.x + fraction * track.w, track.y + 0.5);
|
||||||
|
let value = |v: f64| Some(InputValue::Number(NumberValue { value: v }));
|
||||||
|
rig.send(down(along(0.0)));
|
||||||
|
assert_eq!(rig.draft("level"), value(20.0), "{mode:?}: the track's left edge is the minimum");
|
||||||
|
rig.send(mv(along(0.47)));
|
||||||
|
assert_eq!(rig.draft("level"), value(70.0), "{mode:?}: 20 + 47 = 67 snaps to 70 from 20");
|
||||||
|
rig.send(mv(along(1.0)));
|
||||||
|
assert_eq!(rig.draft("level"), value(120.0), "{mode:?}");
|
||||||
|
// A move that is not a position is not a value.
|
||||||
|
rig.send(mv((f32::NAN, track.y)));
|
||||||
|
assert_eq!(rig.draft("level"), value(120.0), "{mode:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_track_that_shrinks_to_nothing_mid_drag_leaves_the_draft_as_it_was() {
|
||||||
|
for mode in MODES {
|
||||||
|
let mut rig = Rig::new(Port::new(), &controls_surface(), mode);
|
||||||
|
let track = rig.rect("level");
|
||||||
|
let value = |v: f64| Some(InputValue::Number(NumberValue { value: v }));
|
||||||
|
rig.send(down((track.x + 0.5 * track.w, track.y + 0.5)));
|
||||||
|
assert_eq!(rig.draft("level"), value(50.0), "{mode:?}");
|
||||||
|
// The surface shrinks under the pointer: the slider's rect is now zero wide.
|
||||||
|
for placed in rig.rendered.placed.iter_mut().filter(|placed| placed.id.as_str() == "level") {
|
||||||
|
placed.rect.w = 0.0;
|
||||||
|
}
|
||||||
|
// At the track's left edge (0 over 0) and past it (n over 0): neither is a value.
|
||||||
|
for x in [track.x, track.x + 10.0] {
|
||||||
|
rig.send(mv((x, track.y + 0.5)));
|
||||||
|
assert_eq!(rig.draft("level"), value(50.0), "{mode:?}: a move over a zero-width track at {x}");
|
||||||
|
}
|
||||||
|
rig.send(up((track.x, track.y)));
|
||||||
|
let minted = rig.minted();
|
||||||
|
assert_eq!(minted.len(), 1, "{mode:?}");
|
||||||
|
assert_eq!(minted[0].captured[0].value, InputValue::Number(NumberValue { value: 50.0 }), "{mode:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_slider_with_no_range_or_a_step_of_zero_is_handled_by_what_it_declares() {
|
||||||
|
for mode in MODES {
|
||||||
|
for (min, max) in [(5.0, 5.0), (0.0, f64::INFINITY), (9.0, 3.0)] {
|
||||||
|
let mut rig = Rig::new(Port::new(), &lone_slider(min, max, 1.0), mode);
|
||||||
|
let at = inside(rig.rect("level"));
|
||||||
|
rig.click(at);
|
||||||
|
assert_eq!((rig.draft("level"), rig.minted()), (None, vec![]), "{mode:?} {min}..{max}");
|
||||||
|
}
|
||||||
|
// No step: the raw position, unsnapped.
|
||||||
|
let mut rig = Rig::new(Port::new(), &lone_slider(0.0, 100.0, 0.0), mode);
|
||||||
|
let track = rig.rect("level");
|
||||||
|
rig.send(down((track.x + 0.25 * track.w, track.y + 0.5)));
|
||||||
|
assert_eq!(rig.draft("level"), Some(InputValue::Number(NumberValue { value: 25.0 })), "{mode:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_press_on_a_text_input_or_a_select_does_not_fall_through_to_the_button_around_it() {
|
||||||
|
let (input, select) = fields();
|
||||||
|
let card = Node::Button(ButtonNode {
|
||||||
|
common: common("card"),
|
||||||
|
content: vec![fixed("pad", 160.0, 16.0), input, select],
|
||||||
|
on_activate: command("go"),
|
||||||
|
enabled: lit_bool(true),
|
||||||
|
});
|
||||||
|
for mode in MODES {
|
||||||
|
let document = surface(column("root", None, Overflow::Visible, vec![card.clone()]), vec![decl("go", &[])]);
|
||||||
|
let mut rig = Rig::new(Port::new(), &document, mode);
|
||||||
|
for id in ["field", "choice"] {
|
||||||
|
let r = rig.rect(id);
|
||||||
|
assert!(r.w >= 1.0 && r.h >= 1.0, "{mode:?} {id}");
|
||||||
|
assert_eq!(rig.click(inside(r)), vec![], "{mode:?} {id}");
|
||||||
|
}
|
||||||
|
assert_eq!(rig.minted(), vec![], "{mode:?}: the card around them was not pressed");
|
||||||
|
// The card itself still is.
|
||||||
|
rig.click(inside(rig.rect("pad")));
|
||||||
|
assert_eq!(commands_of(&rig.minted()), ["go"], "{mode:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_wheel_that_is_not_a_number_or_runs_on_a_bad_scale_is_ignored_or_taken_at_one() {
|
||||||
|
let mut rig = Rig::new(Port::new(), &nested_surface(), (Metrics::Pixels, 1.5));
|
||||||
|
let over = inside(rig.rect("inner"));
|
||||||
|
// The scale the host gave is not usable: the offset is the wheel's units as they are.
|
||||||
|
for bad in [0.0, f32::INFINITY, f32::NAN, -2.0] {
|
||||||
|
rig.scroll = ScrollOffsets::default();
|
||||||
|
rig.scale = bad;
|
||||||
|
rig.send(wheel(over, (0.0, 10.0), WheelUnit::Units));
|
||||||
|
assert_eq!(rig.offset("inner"), Some((0.0, 10.0)), "scale {bad}");
|
||||||
|
}
|
||||||
|
// A delta that is not a number moves nothing, and does not reset what is scrolled.
|
||||||
|
rig.scale = 1.5;
|
||||||
|
rig.scroll.set(nid("inner"), (0.0, 30.0));
|
||||||
|
for bad in [f32::NAN, f32::INFINITY] {
|
||||||
|
rig.send(wheel(over, (0.0, bad), WheelUnit::Units));
|
||||||
|
rig.send(wheel(over, (bad, 0.0), WheelUnit::Units));
|
||||||
|
assert_eq!(rig.offset("inner"), Some((0.0, 30.0)), "delta {bad}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_wheel_scrolls_the_horizontal_axis_by_its_own_delta() {
|
||||||
|
let pane = column("pane", Some((160.0, 80.0)), Overflow::Scroll, vec![fixed("wide", 400.0, 400.0)]);
|
||||||
|
let document = surface(column("root", None, Overflow::Visible, vec![pane]), vec![]);
|
||||||
|
for mode in MODES {
|
||||||
|
let mut rig = Rig::new(Port::new(), &document, mode);
|
||||||
|
let k = if mode.0 == Metrics::Pixels { mode.1 } else { 1.0 };
|
||||||
|
let over = inside(rig.rect("pane"));
|
||||||
|
assert!(rig.max_scroll("pane").0 > 0.0 && rig.max_scroll("pane").1 > 0.0, "{mode:?}");
|
||||||
|
rig.send(wheel(over, (8.0, 4.0), WheelUnit::Units));
|
||||||
|
assert_eq!(rig.offset("pane"), Some((8.0 * k, 4.0 * k)), "{mode:?}");
|
||||||
|
rig.send(wheel(over, (-2.0, 0.0), WheelUnit::Units));
|
||||||
|
assert_eq!(rig.offset("pane"), Some((6.0 * k, 4.0 * k)), "{mode:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
255
crates/thing-core/src/layout/measure.rs
Normal file
255
crates/thing-core/src/layout/measure.rs
Normal file
|
|
@ -0,0 +1,255 @@
|
||||||
|
//! The Measure seam: what a leaf's intrinsic size is. Text, controls and images are sized by a
|
||||||
|
//! `Measure` the frame owner composes (cut 9a ships Pixels and Cells); layout never estimates
|
||||||
|
//! them. Taffy's own types stop at this file: `Leaf` and `Constraint` are plain data.
|
||||||
|
|
||||||
|
use taffy::{AvailableSpace, Size};
|
||||||
|
use thing_contract::NodeId;
|
||||||
|
|
||||||
|
use crate::bind::Bound;
|
||||||
|
use super::ControlForm;
|
||||||
|
use crate::text::CellText;
|
||||||
|
|
||||||
|
/// The room a leaf is offered on one axis.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
|
pub enum Avail {
|
||||||
|
Definite(f32),
|
||||||
|
MinContent,
|
||||||
|
MaxContent,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a leaf is asked, in logical px (Pixels) or cells (Cells). `known` is a size the parent
|
||||||
|
/// already fixed on an axis; `available` is the room on each axis, `[width, height]`.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
|
pub struct Constraint {
|
||||||
|
pub known: [Option<f32>; 2],
|
||||||
|
pub available: [Avail; 2],
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A leaf node with the values it shows, borrowed from the bound tree.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub enum Leaf<'a> {
|
||||||
|
Text { node: &'a NodeId, content: &'a Bound, style_token: &'a str, wrap: bool, max_lines: Option<u32> },
|
||||||
|
TextInput { node: &'a NodeId, multiline: bool, placeholder: &'a Bound, value: &'a Bound },
|
||||||
|
Toggle { node: &'a NodeId },
|
||||||
|
Slider { node: &'a NodeId },
|
||||||
|
Select { node: &'a NodeId, selected: &'a Bound },
|
||||||
|
Image { node: &'a NodeId, asset: &'a Bound },
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A face the text engine drew with. Opaque to core: the backend maps it to its own font.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub struct FontId(pub u32);
|
||||||
|
|
||||||
|
/// One placed glyph of a line: the engine's glyph id and its position in the line, logical px.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
|
pub struct Glyph {
|
||||||
|
pub id: u32,
|
||||||
|
pub x: f32,
|
||||||
|
pub y: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||||
|
pub struct CellStyle {
|
||||||
|
pub bold: bool,
|
||||||
|
pub italic: bool,
|
||||||
|
pub underline: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What one line of text is made of: shaped glyphs (Pixels) or characters (Cells).
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub enum Run {
|
||||||
|
Glyphs { font: FontId, size: f32, glyphs: Vec<Glyph> },
|
||||||
|
Cells { text: CellText, style: CellStyle },
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The Text leaf a line breaker is asked to lay out.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct TextRequest<'a> {
|
||||||
|
pub node: &'a NodeId,
|
||||||
|
pub text: &'a str,
|
||||||
|
pub style_token: &'a str,
|
||||||
|
pub wrap: bool,
|
||||||
|
pub max_lines: Option<u32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One line: `y` and `height` are measured from the top of the node, in logical px or cells.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct TextLine {
|
||||||
|
pub y: f32,
|
||||||
|
pub height: f32,
|
||||||
|
pub run: Run,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq)]
|
||||||
|
pub struct TextLayout {
|
||||||
|
pub lines: Vec<TextLine>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The intrinsic size `(width, height)` of a leaf under a constraint. A non-finite or negative
|
||||||
|
/// answer is taken as zero. `text` is the same engine's answer for a Text leaf at its final
|
||||||
|
/// width: the lines `measure` sized the leaf for, broken and shaped. Wrap and `max_lines` are the
|
||||||
|
/// engine's; render never breaks a line.
|
||||||
|
pub trait Measure {
|
||||||
|
fn measure(&mut self, leaf: &Leaf, constraint: Constraint) -> (f32, f32);
|
||||||
|
fn text(&mut self, request: &TextRequest, width: f32) -> TextLayout;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The largest length, in device px or cells, a style or a measure may state: 2^21 = 2,097,152.
|
||||||
|
/// f32 has 24 mantissa bits, so a coordinate below 2^24 is exact to a whole pixel and one below
|
||||||
|
/// 2^21 keeps 3 fractional bits, 1/8 px. A coordinate is a sum of lengths along an axis: eight
|
||||||
|
/// maximal siblings still sum below 2^24 (whole-pixel exact), and any run of siblings whose
|
||||||
|
/// extents sum below 2^21 keeps 1/8 px. A length beyond the bound is an invalid style value and a
|
||||||
|
/// larger measured size is clamped to it.
|
||||||
|
pub(crate) const MAX_DEVICE: f32 = 2_097_152.0;
|
||||||
|
|
||||||
|
/// The smallest nonzero extent a measure may state: 1/8 px, the precision the length bound
|
||||||
|
/// leaves. A smaller side is below the resolution layout keeps.
|
||||||
|
pub(super) const MIN_SIDE: f32 = 0.125;
|
||||||
|
|
||||||
|
/// The fewest rows a Cells control needs to be `Bordered`: a border row above and below a content row.
|
||||||
|
pub(super) const BORDERED_ROWS: f32 = 3.0;
|
||||||
|
|
||||||
|
/// Device px per cell, `(across, down)`: the metric a terminal cell stands for. In Cells mode a Px
|
||||||
|
/// length converts at it (8 wide, 16 tall), and an Image's pixel extent is read in cells at it.
|
||||||
|
pub(crate) const CELL_PX: (f32, f32) = (8.0, 16.0);
|
||||||
|
|
||||||
|
/// The axis a Px length runs along: across (width, left and right, columns) or down (height, top
|
||||||
|
/// and bottom, rows). A cell is not square, so a Px length converts per axis in Cells.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub(super) enum Axis {
|
||||||
|
X,
|
||||||
|
Y,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The one place logical units become device units and back: `k` device px per logical px
|
||||||
|
/// (1 in Cells, where `length` divides a Px length by the cell metric instead). Everything past
|
||||||
|
/// this adapter, the style map and the solver included, is device.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub(super) struct Device {
|
||||||
|
k: f32,
|
||||||
|
cells: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Device {
|
||||||
|
pub(super) fn new(k: f32, cells: bool) -> Self {
|
||||||
|
Self { k, cells }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The least a Use placeholder takes, so its error is visible: 16 logical px each way.
|
||||||
|
pub(super) fn placeholder(self) -> (f32, f32) {
|
||||||
|
(self.length(16.0, Axis::X), self.length(16.0, Axis::Y))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether this is a cell grid.
|
||||||
|
pub(super) fn cells(self) -> bool {
|
||||||
|
self.cells
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A Plot's size: the CSS default object size, 300x150 logical px. A plot is sized by layout,
|
||||||
|
/// never measured.
|
||||||
|
pub(super) fn plot(self) -> (f32, f32) {
|
||||||
|
(self.length(300.0, Axis::X), self.length(150.0, Axis::Y))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A viewport side or a measured size in device units: logical px times the scale, or cells
|
||||||
|
/// as they are (a Measure answers in cells in Cells).
|
||||||
|
pub(super) fn px(self, logical: f32) -> f32 {
|
||||||
|
logical * self.k
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A Px length of the document in device units along `axis`: times the scale in Pixels, divided
|
||||||
|
/// by the cell metric in Cells. Taffy's rounding then lands it on a device pixel or a cell.
|
||||||
|
pub(super) fn length(self, px: f32, axis: Axis) -> f32 {
|
||||||
|
if self.cells {
|
||||||
|
px / match axis {
|
||||||
|
Axis::X => CELL_PX.0,
|
||||||
|
Axis::Y => CELL_PX.1,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
px * self.k
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A border side of `px` along `axis`: its Px length, and in Cells at least one cell when it is
|
||||||
|
/// nonzero, so the terminal shows the border and content never sits under it. Zero stays zero.
|
||||||
|
pub(super) fn border(self, px: f32, axis: Axis) -> f32 {
|
||||||
|
let length = self.length(px, axis);
|
||||||
|
if self.cells && px > 0.0 { length.max(1.0) } else { length }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A control's form, read off its laid border-box height `h` and the laid height `row` of its
|
||||||
|
/// content node, never fed back to the solve: in Pixels always `Bordered`; in Cells `Bordered`
|
||||||
|
/// from `BORDERED_ROWS` rows and only when the content row fits between the border rows, else
|
||||||
|
/// `Compact` (ruling cells-bordered-needs-content-fit).
|
||||||
|
pub(super) fn form(self, h: f32, row: f32) -> ControlForm {
|
||||||
|
let (_, edge) = self.inset(ControlForm::Bordered, f32::INFINITY, f32::INFINITY);
|
||||||
|
if !self.cells || (h >= BORDERED_ROWS && row + 2.0 * edge <= h) { ControlForm::Bordered } else { ControlForm::Compact }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The inset of a laid control's content from its border box, `(x, y)`, in device units: the one
|
||||||
|
/// rule, owned here. In Pixels: the 2 px of chrome. In Cells a `Bordered` control keeps one cell
|
||||||
|
/// clear on every side, a `Compact` one a cell on each side across and none down. Never more than
|
||||||
|
/// half a side.
|
||||||
|
pub(super) fn inset(self, form: ControlForm, w: f32, h: f32) -> (f32, f32) {
|
||||||
|
let (x, y) = match (self.cells, form) {
|
||||||
|
(false, _) => (self.px(2.0), self.px(2.0)),
|
||||||
|
(true, ControlForm::Bordered) => (1.0, 1.0),
|
||||||
|
(true, ControlForm::Compact) => (1.0, 0.0),
|
||||||
|
};
|
||||||
|
(x.min(w / 2.0).max(0.0), y.min(h / 2.0).max(0.0))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn logical(self, device: f32) -> f32 {
|
||||||
|
device / self.k
|
||||||
|
}
|
||||||
|
|
||||||
|
fn avail(self, space: AvailableSpace) -> Avail {
|
||||||
|
match space {
|
||||||
|
AvailableSpace::Definite(v) => Avail::Definite(self.logical(v)),
|
||||||
|
AvailableSpace::MinContent => Avail::MinContent,
|
||||||
|
AvailableSpace::MaxContent => Avail::MaxContent,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A measure's answer as a device size: non-finite or negative is zero, huge is the bound.
|
||||||
|
fn size(self, (w, h): (f32, f32)) -> Size<f32> {
|
||||||
|
let side = |v: f32| if v.is_finite() && v > 0.0 { self.px(v).min(MAX_DEVICE) } else { 0.0 };
|
||||||
|
Size { width: side(w), height: side(h) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Taffy's leaf callback to `Measure`: device px in, logical out, and back.
|
||||||
|
pub(super) fn measure_leaf(
|
||||||
|
measure: &mut dyn Measure,
|
||||||
|
leaf: &Leaf,
|
||||||
|
dev: Device,
|
||||||
|
known: Size<Option<f32>>,
|
||||||
|
space: Size<AvailableSpace>,
|
||||||
|
) -> Size<f32> {
|
||||||
|
let constraint = Constraint {
|
||||||
|
known: [known.width.map(|v| dev.logical(v)), known.height.map(|v| dev.logical(v))],
|
||||||
|
available: [dev.avail(space.width), dev.avail(space.height)],
|
||||||
|
};
|
||||||
|
dev.size(measure.measure(leaf, constraint))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The aspect ratio an Image keeps when stretched, from what its measure says unconstrained
|
||||||
|
/// (logical px, judged in device px). `Ok(None)` is no extent at all (0x0: nothing known yet).
|
||||||
|
/// Each side must be 0 or within [MIN_SIDE, MAX_DEVICE] and not just one of them zero; the ratio
|
||||||
|
/// is then within [MIN_SIDE / MAX_DEVICE, MAX_DEVICE / MIN_SIDE] = [2^-24, 2^24] by derivation, so
|
||||||
|
/// no second range is checked. Anything else is an invalid measure: `Err`. A side the image takes
|
||||||
|
/// from its ratio is held under MAX_DEVICE by the image's own max size (see the walk).
|
||||||
|
pub(super) fn intrinsic_ratio(measure: &mut dyn Measure, leaf: &Leaf, dev: Device) -> Result<Option<f32>, ()> {
|
||||||
|
let constraint = Constraint { known: [None, None], available: [Avail::MaxContent, Avail::MaxContent] };
|
||||||
|
let (w, h) = measure.measure(leaf, constraint);
|
||||||
|
let (w, h) = (dev.px(w), dev.px(h));
|
||||||
|
let legal = |v: f32| v == 0.0 || (v.is_finite() && (MIN_SIDE..=MAX_DEVICE).contains(&v));
|
||||||
|
if !legal(w) || !legal(h) {
|
||||||
|
return Err(());
|
||||||
|
}
|
||||||
|
match (w == 0.0, h == 0.0) {
|
||||||
|
(true, true) => Ok(None),
|
||||||
|
(false, false) => Ok(Some(w / h)),
|
||||||
|
_ => Err(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
264
crates/thing-core/src/layout/mod.rs
Normal file
264
crates/thing-core/src/layout/mod.rs
Normal file
|
|
@ -0,0 +1,264 @@
|
||||||
|
//! Layout: a `BoundTree` and a `LayoutFrame` become the geometry of every node, solved by Taffy
|
||||||
|
//! (the one solver) and handed back as plain rectangles. A pure function: it reads no port, no
|
||||||
|
//! clock and no state, builds a fresh Taffy tree per call and keeps none.
|
||||||
|
//!
|
||||||
|
//! Pixels mode runs the solver in device pixels (every Px length and every measured size is
|
||||||
|
//! multiplied by the scale factor at the one adapter) with Taffy's cumulative rounding, so every
|
||||||
|
//! edge lands on a device pixel and adjacent boxes share it. Cells mode ignores the scale and converts a Px length at the cell metric (8x16 device px per cell). The
|
||||||
|
//! viewport is a block container the document root flows in, and is not itself in the output.
|
||||||
|
//! Overlays are out of flow: after the main pass each is laid out as its own root against its anchor
|
||||||
|
//! and appended after every main-tree node.
|
||||||
|
|
||||||
|
mod measure;
|
||||||
|
mod overlay;
|
||||||
|
mod style;
|
||||||
|
mod tree;
|
||||||
|
|
||||||
|
use taffy::{AvailableSpace, Size, compute_leaf_layout};
|
||||||
|
use measure::Device;
|
||||||
|
use thing_contract::{NodeId, OverlayNode};
|
||||||
|
|
||||||
|
pub use measure::{Avail, CellStyle, Constraint, FontId, Glyph, Leaf, Measure, Run, TextLayout, TextLine, TextRequest};
|
||||||
|
pub(crate) use measure::{CELL_PX, MAX_DEVICE};
|
||||||
|
|
||||||
|
use crate::bind::BoundTree;
|
||||||
|
use crate::diagnostic::{Code, Diagnostic};
|
||||||
|
|
||||||
|
/// The stack one level of nesting takes inside Taffy's recursion, worst of Flex, Grid, Block and
|
||||||
|
/// scroll boxes, measured in a debug build by `stack_per_level` in tests/layout.rs, doubled.
|
||||||
|
/// Taffy recurses natively and nothing in it can be wrapped per level, so the walk's depth is
|
||||||
|
/// known first and the one segment is sized for it.
|
||||||
|
const STACK_PER_LEVEL: usize = 96 * 1024;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Metrics {
|
||||||
|
Pixels,
|
||||||
|
Cells,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The room one layout fills. `viewport` is logical px (Pixels) or cells (Cells); `scale` is the
|
||||||
|
/// device pixels per logical px and is ignored in Cells.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
|
pub struct LayoutFrame {
|
||||||
|
pub viewport: (f32, f32),
|
||||||
|
pub scale: f32,
|
||||||
|
pub metrics: Metrics,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
|
pub struct Rect {
|
||||||
|
pub x: f32,
|
||||||
|
pub y: f32,
|
||||||
|
pub w: f32,
|
||||||
|
pub h: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One node's geometry. `rect` is the absolute border box in device px (Pixels) or cells, and is
|
||||||
|
/// unscrolled. `parent` indexes the nearest laid ancestor in `LaidTree.nodes` (none for the
|
||||||
|
/// document root and every overlay root). `content` is the scrollable content size of an
|
||||||
|
/// `Overflow::Scroll` node; `clip` is the padding box (the border box inset by the laid border)
|
||||||
|
/// of a Clip or Scroll node.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct LaidNode {
|
||||||
|
pub id: NodeId,
|
||||||
|
pub parent: Option<u32>,
|
||||||
|
pub rect: Rect,
|
||||||
|
pub content: Option<(f32, f32)>,
|
||||||
|
/// How far `content` reaches past the padding box, never negative: the furthest the content
|
||||||
|
/// may scroll. Input clamps its position here; render and hit-test translate the children by
|
||||||
|
/// it. Layout never sees a scroll position, so a scroll never re-runs layout.
|
||||||
|
pub max_scroll: Option<(f32, f32)>,
|
||||||
|
pub clip: Option<Rect>,
|
||||||
|
/// A control's (Button, TextInput, Select, Toggle) form and content box, stated by layout; render
|
||||||
|
/// draws what this says and infers nothing from geometry. `None` for every other node.
|
||||||
|
pub control: Option<LaidControl>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The two forms of a control. In Pixels every control is `Bordered` (render draws chrome behind its
|
||||||
|
/// content). In Cells a control laid 3 rows or taller is `Bordered`: its border stands in the edge
|
||||||
|
/// cells and its content keeps one cell clear on every side. A control laid shorter is `Compact`: its
|
||||||
|
/// one-row affordance on the first row, one cell each side.
|
||||||
|
///
|
||||||
|
/// The form is a function of the laid border-box height alone (`Device::form`), read after the one
|
||||||
|
/// solve. A content-sized control is at least 3 rows because its border rows are in its max-content
|
||||||
|
/// height, not its min-content height: a short container still squeezes it to one compact row.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum ControlForm {
|
||||||
|
Bordered,
|
||||||
|
Compact,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A laid control: the form layout chose and the box its content is laid or drawn in, in device px
|
||||||
|
/// (Pixels) or cells: the border box less the form's inset. A Pixels Button's content is laid
|
||||||
|
/// without an inset, so its content box is its border box. `Compact` is the form of a control whose
|
||||||
|
/// content row does not fit between the border rows: its content stands from the first row and runs
|
||||||
|
/// past the last, so a painter clips a `Compact` control to its rect.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||||
|
pub struct LaidControl {
|
||||||
|
pub form: ControlForm,
|
||||||
|
pub content: Rect,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every laid node in paint order (document order, Repeat instances spliced), and the style
|
||||||
|
/// values that were not legal.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct LaidTree {
|
||||||
|
pub nodes: Vec<LaidNode>,
|
||||||
|
pub diagnostics: Vec<Diagnostic>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whole numbers stay whole, and negative zero is written as zero.
|
||||||
|
fn clean(v: f32) -> f32 {
|
||||||
|
if v == 0.0 || !v.is_finite() { 0.0 } else { v }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a frame was refused: nothing is laid out in a room that is not a finite positive size.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum FrameError {
|
||||||
|
/// The scale is not finite, not positive or past 1024 (Pixels only).
|
||||||
|
Scale,
|
||||||
|
/// A viewport side is not finite, not positive or past the length bound.
|
||||||
|
Viewport,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why no layout came back. The frame owner keeps the last good `LaidTree` on either and shows
|
||||||
|
/// the diagnostic of `OutOfRange` (code `LayoutOutOfRange`, naming the first offending node in
|
||||||
|
/// document order).
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub enum LayoutError {
|
||||||
|
Frame(FrameError),
|
||||||
|
OutOfRange(Diagnostic),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<FrameError> for LayoutError {
|
||||||
|
fn from(error: FrameError) -> Self {
|
||||||
|
LayoutError::Frame(error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn layout(tree: &BoundTree, frame: &LayoutFrame, measure: &mut dyn Measure) -> Result<LaidTree, LayoutError> {
|
||||||
|
let k = match frame.metrics {
|
||||||
|
Metrics::Cells => 1.0,
|
||||||
|
Metrics::Pixels if frame.scale.is_finite() && frame.scale > 0.0 && frame.scale <= 1024.0 => frame.scale,
|
||||||
|
Metrics::Pixels => return Err(FrameError::Scale.into()),
|
||||||
|
};
|
||||||
|
let dev = Device::new(k, frame.metrics == Metrics::Cells);
|
||||||
|
let side = |v: f32| (v.is_finite() && v > 0.0 && dev.px(v) <= MAX_DEVICE).then(|| dev.px(v));
|
||||||
|
let (Some(vw), Some(vh)) = (side(frame.viewport.0), side(frame.viewport.1)) else {
|
||||||
|
return Err(FrameError::Viewport.into());
|
||||||
|
};
|
||||||
|
let mut nodes = Vec::new();
|
||||||
|
let mut diagnostics = Vec::new();
|
||||||
|
let overlays = solve(tree, tree::Top::Document, dev, (vw, vh), (0.0, 0.0), measure, &mut nodes, &mut diagnostics)?;
|
||||||
|
overlay::place_all(tree, dev, (vw, vh), overlays, measure, &mut nodes, &mut diagnostics)?;
|
||||||
|
Ok(LaidTree { nodes, diagnostics })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run the one solve over a built tree in `size` device px.
|
||||||
|
fn compute(built: &mut tree::Built, dev: Device, size: (f32, f32), measure: &mut dyn Measure) {
|
||||||
|
let tree::Built { taffy, root, entries, leaves, .. } = built;
|
||||||
|
let space = Size { width: AvailableSpace::Definite(size.0), height: AvailableSpace::Definite(size.1) };
|
||||||
|
// Entries come parent first, so one pass finds the deepest; the viewport and a spare few add.
|
||||||
|
let mut depth = vec![1usize; entries.len()];
|
||||||
|
for (i, entry) in entries.iter().enumerate() {
|
||||||
|
depth[i] = entry.parent.map_or(1, |parent| depth[parent] + 1);
|
||||||
|
}
|
||||||
|
let levels = depth.iter().copied().max().unwrap_or(0) + 8;
|
||||||
|
stacker::grow(STACK_PER_LEVEL * levels, || {
|
||||||
|
taffy
|
||||||
|
.compute_layout_with_measure(*root, space, |inputs, _, context, style| {
|
||||||
|
let leaf = context.and_then(|index| leaves.get(*index));
|
||||||
|
compute_leaf_layout(
|
||||||
|
inputs,
|
||||||
|
style,
|
||||||
|
|_, _| 0.0,
|
||||||
|
|known, space| match leaf {
|
||||||
|
Some(leaf) => measure::measure_leaf(measure, leaf, dev, known, space),
|
||||||
|
None => Size::ZERO,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.expect("taffy: the root is in the tree")
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build and solve one Taffy tree in `size` device px, its origin at `origin`, and append its laid
|
||||||
|
/// nodes (absolute, in entry order) and its diagnostics. Returns the Overlays the tree met in flow.
|
||||||
|
///
|
||||||
|
/// One build, one solve: a control's form is read off the height Taffy laid it, never fed back.
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
fn solve<'a>(
|
||||||
|
tree: &'a BoundTree,
|
||||||
|
top: tree::Top<'a>,
|
||||||
|
dev: Device,
|
||||||
|
size: (f32, f32),
|
||||||
|
origin: (f32, f32),
|
||||||
|
measure: &mut dyn Measure,
|
||||||
|
nodes: &mut Vec<LaidNode>,
|
||||||
|
diagnostics: &mut Vec<Diagnostic>,
|
||||||
|
) -> Result<Vec<&'a OverlayNode>, LayoutError> {
|
||||||
|
let mut built = tree::build(tree, dev, top, size, measure);
|
||||||
|
compute(&mut built, dev, size, measure);
|
||||||
|
let tree::Built { taffy, entries, diagnostics: own, overlays, .. } = &mut built;
|
||||||
|
let base = nodes.len();
|
||||||
|
let mut absolute: Vec<(f32, f32)> = Vec::with_capacity(entries.len());
|
||||||
|
for entry in entries.iter() {
|
||||||
|
let laid = taffy.layout(entry.node).expect("taffy: node is in the tree");
|
||||||
|
let (px, py) = entry.parent.map_or(origin, |parent| absolute[parent]);
|
||||||
|
let (x, y) = (px + laid.location.x, py + laid.location.y);
|
||||||
|
let (w, h) = (laid.size.width, laid.size.height);
|
||||||
|
// The content row's laid height. A control without a content node (a Pixels Button, a
|
||||||
|
// non-control) passes `h`, which the form never reads.
|
||||||
|
let row = entry.control.and_then(|c| c.inner).map_or(h, |inner| taffy.layout(inner).expect("taffy: node is in the tree").size.height);
|
||||||
|
let form = dev.form(h, row);
|
||||||
|
let (ix, iy) = entry.control.filter(|c| c.inset).map_or((0.0, 0.0), |_| dev.inset(form, w, h));
|
||||||
|
// The origin the children are placed from: a control's content node sits where the inset
|
||||||
|
// says, not where Taffy put it.
|
||||||
|
absolute.push(if entry.control.is_some_and(|c| c.inner.is_some()) { (x + ix, y + iy) } else { (x, y) });
|
||||||
|
// Taffy's content extent is measured from the padding box. `content` is never smaller than
|
||||||
|
// the border box; `max_scroll` is what the content reaches past the padding box.
|
||||||
|
let reached = entry.scroll.then(|| {
|
||||||
|
let overflow = laid.scrollable_overflow_rect.rect();
|
||||||
|
let round = |v: f32| (v + 0.5).floor();
|
||||||
|
(round(overflow.right), round(overflow.bottom))
|
||||||
|
});
|
||||||
|
let content = reached.map(|(cw, ch)| (clean(cw.max(w)), clean(ch.max(h))));
|
||||||
|
let max_scroll = reached.map(|(cw, ch)| {
|
||||||
|
let inner_w = w - laid.border.left - laid.border.right;
|
||||||
|
let inner_h = h - laid.border.top - laid.border.bottom;
|
||||||
|
(clean((cw - inner_w).max(0.0)), clean((ch - inner_h).max(0.0)))
|
||||||
|
});
|
||||||
|
// Precision is a property of the whole layout: a position or an extent past the bound
|
||||||
|
// (a sum along an axis included) refuses it, so no value is silently rounded.
|
||||||
|
let reach = [x, y, x + w, y + h, content.map_or(0.0, |c| c.0), content.map_or(0.0, |c| c.1)];
|
||||||
|
if reach.iter().any(|v| !v.is_finite() || v.abs() > MAX_DEVICE) {
|
||||||
|
return Err(LayoutError::OutOfRange(Diagnostic {
|
||||||
|
code: Code::LayoutOutOfRange,
|
||||||
|
surface: tree.resolved().document().record_key(),
|
||||||
|
node: Some(entry.id.clone()),
|
||||||
|
detail: "position or extent past the precision bound".to_string(),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
let clip = entry.clip.then(|| Rect {
|
||||||
|
x: clean(x + laid.border.left),
|
||||||
|
y: clean(y + laid.border.top),
|
||||||
|
w: clean(w - laid.border.left - laid.border.right),
|
||||||
|
h: clean(h - laid.border.top - laid.border.bottom),
|
||||||
|
});
|
||||||
|
let control = entry.control.map(|_| LaidControl {
|
||||||
|
form,
|
||||||
|
content: Rect { x: clean(x + ix), y: clean(y + iy), w: clean(w - 2.0 * ix), h: clean(h - 2.0 * iy) },
|
||||||
|
});
|
||||||
|
nodes.push(LaidNode {
|
||||||
|
id: entry.id.clone(),
|
||||||
|
parent: entry.parent.map(|parent| (base + parent) as u32),
|
||||||
|
rect: Rect { x: clean(x), y: clean(y), w: clean(w), h: clean(h) },
|
||||||
|
content,
|
||||||
|
max_scroll,
|
||||||
|
clip,
|
||||||
|
control,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
diagnostics.append(own);
|
||||||
|
Ok(std::mem::take(overlays))
|
||||||
|
}
|
||||||
55
crates/thing-core/src/layout/overlay.rs
Normal file
55
crates/thing-core/src/layout/overlay.rs
Normal file
|
|
@ -0,0 +1,55 @@
|
||||||
|
//! The overlay pass: each Overlay is its own Taffy root, laid out against its anchor after the
|
||||||
|
//! main pass and appended after every main-tree node, which is the paint order (overlays last).
|
||||||
|
//! The viewport and a node anchor share one placement: the anchor's rect is the overlay's origin
|
||||||
|
//! and size.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use thing_contract::{Anchor, NodeId, OverlayNode};
|
||||||
|
|
||||||
|
use super::measure::Device;
|
||||||
|
use super::tree::Top;
|
||||||
|
use super::{LaidNode, LayoutError, Measure, Rect, solve};
|
||||||
|
use crate::bind::BoundTree;
|
||||||
|
use crate::diagnostic::{Code, Diagnostic};
|
||||||
|
|
||||||
|
/// Lay out `first` and every Overlay nested in them: each Overlay before the Overlays inside it,
|
||||||
|
/// in document order, so an anchor inside an earlier Overlay resolves. An anchor that is not laid
|
||||||
|
/// (hidden, absent) places the overlay against the viewport and is named once.
|
||||||
|
pub(super) fn place_all<'a>(
|
||||||
|
tree: &'a BoundTree,
|
||||||
|
dev: Device,
|
||||||
|
viewport: (f32, f32),
|
||||||
|
first: Vec<&'a OverlayNode>,
|
||||||
|
measure: &mut dyn Measure,
|
||||||
|
nodes: &mut Vec<LaidNode>,
|
||||||
|
diagnostics: &mut Vec<Diagnostic>,
|
||||||
|
) -> Result<(), LayoutError> {
|
||||||
|
let mut rects: HashMap<NodeId, Rect> = nodes.iter().map(|n| (n.id.clone(), n.rect)).collect();
|
||||||
|
let mut pending: Vec<&OverlayNode> = first;
|
||||||
|
pending.reverse();
|
||||||
|
while let Some(overlay) = pending.pop() {
|
||||||
|
let anchor = match &overlay.anchor {
|
||||||
|
Anchor::Viewport => Rect { x: 0.0, y: 0.0, w: viewport.0, h: viewport.1 },
|
||||||
|
Anchor::Node(anchor) => match rects.get(&anchor.node) {
|
||||||
|
Some(rect) => *rect,
|
||||||
|
None => {
|
||||||
|
diagnostics.push(Diagnostic {
|
||||||
|
code: Code::OverlayAnchorMissing,
|
||||||
|
surface: tree.resolved().document().record_key(),
|
||||||
|
node: Some(overlay.common.id.clone()),
|
||||||
|
detail: anchor.node.as_str().to_string(),
|
||||||
|
});
|
||||||
|
Rect { x: 0.0, y: 0.0, w: viewport.0, h: viewport.1 }
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
|
let start = nodes.len();
|
||||||
|
let nested = solve(tree, Top::Overlay(overlay), dev, (anchor.w, anchor.h), (anchor.x, anchor.y), measure, nodes, diagnostics)?;
|
||||||
|
for node in &nodes[start..] {
|
||||||
|
rects.entry(node.id.clone()).or_insert(node.rect);
|
||||||
|
}
|
||||||
|
pending.extend(nested.into_iter().rev());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
295
crates/thing-core/src/layout/style.rs
Normal file
295
crates/thing-core/src/layout/style.rs
Normal file
|
|
@ -0,0 +1,295 @@
|
||||||
|
//! The one style map: `BoxStyle` and `Paint` onto Taffy's `Style`. The destructure names every
|
||||||
|
//! contract field, so a new field fails to compile until it is mapped.
|
||||||
|
//!
|
||||||
|
//! A slot holding a value its CSS counterpart forbids (a non-finite or oversized number, a
|
||||||
|
//! negative where none is allowed, a Dimension arm the slot cannot take) takes its initial value
|
||||||
|
//! and is reported once by field name. `Percent` is authored in percent points (50 is half).
|
||||||
|
|
||||||
|
use taffy::style_helpers::TaffyZero;
|
||||||
|
use taffy::{
|
||||||
|
AlignContent, AlignItems, Dimension, Display as TDisplay, FlexDirection, FlexWrap, GridTemplateComponent,
|
||||||
|
LengthPercentage, LengthPercentageAuto, MaxTrackSizingFunction, MinTrackSizingFunction, Overflow as TOverflow,
|
||||||
|
Point, Position as TPosition, Rect, Size, Style, TrackSizingFunction,
|
||||||
|
};
|
||||||
|
use thing_contract as c;
|
||||||
|
|
||||||
|
use super::measure::{Axis, Device, MAX_DEVICE};
|
||||||
|
|
||||||
|
/// Field names of the slots that took their initial value.
|
||||||
|
pub(super) type Invalid = Vec<&'static str>;
|
||||||
|
|
||||||
|
fn number(value: f64, negative: bool) -> Option<f32> {
|
||||||
|
let fits = value.is_finite() && value.abs() <= f64::from(MAX_DEVICE) && (negative || value >= 0.0);
|
||||||
|
fits.then_some(value as f32)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn length(scalar: &c::Scalar, dev: Device, axis: Axis, negative: bool) -> Option<f32> {
|
||||||
|
number(scalar.value, negative).map(|v| dev.length(v, axis)).filter(|v| v.abs() <= MAX_DEVICE)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn percent(scalar: &c::Scalar, negative: bool) -> Option<f32> {
|
||||||
|
number(scalar.value, negative).map(|v| v / 100.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lp(d: &c::Dimension, dev: Device, axis: Axis) -> Option<LengthPercentage> {
|
||||||
|
match d {
|
||||||
|
c::Dimension::Px(s) => length(s, dev, axis, false).map(LengthPercentage::length),
|
||||||
|
c::Dimension::Percent(s) => percent(s, false).map(LengthPercentage::percent),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lpa(d: &c::Dimension, dev: Device, axis: Axis, negative: bool) -> Option<LengthPercentageAuto> {
|
||||||
|
match d {
|
||||||
|
c::Dimension::Px(s) => length(s, dev, axis, negative).map(LengthPercentageAuto::length),
|
||||||
|
c::Dimension::Percent(s) => percent(s, negative).map(LengthPercentageAuto::percent),
|
||||||
|
c::Dimension::Auto => Some(LengthPercentageAuto::auto()),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn size_dim(d: &c::Dimension, dev: Device, axis: Axis) -> Option<Dimension> {
|
||||||
|
match d {
|
||||||
|
c::Dimension::Px(s) => length(s, dev, axis, false).map(Dimension::length),
|
||||||
|
c::Dimension::Percent(s) => percent(s, false).map(Dimension::percent),
|
||||||
|
c::Dimension::Auto => Some(Dimension::auto()),
|
||||||
|
c::Dimension::Content => Some(Dimension::fit_content()),
|
||||||
|
c::Dimension::Fr(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn basis_dim(d: &c::Dimension, dev: Device, axis: Axis) -> Option<Dimension> {
|
||||||
|
match d {
|
||||||
|
c::Dimension::Content => Some(Dimension::content()),
|
||||||
|
c::Dimension::Fr(_) => None,
|
||||||
|
other => size_dim(other, dev, axis),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn track(d: &c::Dimension, dev: Device, axis: Axis) -> Option<GridTemplateComponent<String>> {
|
||||||
|
use MaxTrackSizingFunction as Max;
|
||||||
|
use MinTrackSizingFunction as Min;
|
||||||
|
let (min, max) = match d {
|
||||||
|
c::Dimension::Px(s) => {
|
||||||
|
let v = length(s, dev, axis, false)?;
|
||||||
|
(Min::length(v), Max::length(v))
|
||||||
|
}
|
||||||
|
c::Dimension::Percent(s) => {
|
||||||
|
let v = percent(s, false)?;
|
||||||
|
(Min::percent(v), Max::percent(v))
|
||||||
|
}
|
||||||
|
c::Dimension::Fr(s) => (Min::auto(), Max::fr(number(s.value, false)?)),
|
||||||
|
c::Dimension::Auto => (Min::auto(), Max::auto()),
|
||||||
|
c::Dimension::Content => (Min::max_content(), Max::max_content()),
|
||||||
|
};
|
||||||
|
Some(GridTemplateComponent::Single(TrackSizingFunction { min, max }))
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Slots {
|
||||||
|
dev: Device,
|
||||||
|
invalid: Invalid,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Slots {
|
||||||
|
fn take<T>(&mut self, field: &'static str, value: Option<T>, initial: T) -> T {
|
||||||
|
value.unwrap_or_else(|| {
|
||||||
|
if !self.invalid.contains(&field) {
|
||||||
|
self.invalid.push(field);
|
||||||
|
}
|
||||||
|
initial
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn size2(&mut self, field: &'static str, s: &c::Size2) -> Size<Dimension> {
|
||||||
|
let dev = self.dev;
|
||||||
|
Size {
|
||||||
|
width: self.take(field, size_dim(&s.width, dev, Axis::X), Dimension::auto()),
|
||||||
|
height: self.take(field, size_dim(&s.height, dev, Axis::Y), Dimension::auto()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn size2_lpa(&mut self, field: &'static str, s: &c::Size2) -> Size<LengthPercentageAuto> {
|
||||||
|
let dev = self.dev;
|
||||||
|
Size {
|
||||||
|
width: self.take(field, lpa(&s.width, dev, Axis::X, false), LengthPercentageAuto::auto()),
|
||||||
|
height: self.take(field, lpa(&s.height, dev, Axis::Y, false), LengthPercentageAuto::auto()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn edges_lpa(
|
||||||
|
&mut self,
|
||||||
|
field: &'static str,
|
||||||
|
e: &c::Edges,
|
||||||
|
negative: bool,
|
||||||
|
initial: LengthPercentageAuto,
|
||||||
|
) -> Rect<LengthPercentageAuto> {
|
||||||
|
let dev = self.dev;
|
||||||
|
Rect {
|
||||||
|
left: self.take(field, lpa(&e.left, dev, Axis::X, negative), initial),
|
||||||
|
right: self.take(field, lpa(&e.right, dev, Axis::X, negative), initial),
|
||||||
|
top: self.take(field, lpa(&e.top, dev, Axis::Y, negative), initial),
|
||||||
|
bottom: self.take(field, lpa(&e.bottom, dev, Axis::Y, negative), initial),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn edges_lp(&mut self, field: &'static str, e: &c::Edges) -> Rect<LengthPercentage> {
|
||||||
|
let dev = self.dev;
|
||||||
|
let zero = LengthPercentage::ZERO;
|
||||||
|
Rect {
|
||||||
|
left: self.take(field, lp(&e.left, dev, Axis::X), zero),
|
||||||
|
right: self.take(field, lp(&e.right, dev, Axis::X), zero),
|
||||||
|
top: self.take(field, lp(&e.top, dev, Axis::Y), zero),
|
||||||
|
bottom: self.take(field, lp(&e.bottom, dev, Axis::Y), zero),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tracks(&mut self, field: &'static str, axis: Axis, dims: &[c::Dimension]) -> Vec<GridTemplateComponent<String>> {
|
||||||
|
let dev = self.dev;
|
||||||
|
let tracks: Option<Vec<_>> = dims.iter().map(|d| track(d, dev, axis)).collect();
|
||||||
|
self.take(field, tracks, Vec::new())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn weight(&mut self, field: &'static str, value: f64, initial: f32) -> f32 {
|
||||||
|
self.take(field, number(value, false), initial)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn item(align: &c::ItemAlign) -> Option<AlignItems> {
|
||||||
|
Some(match align {
|
||||||
|
c::ItemAlign::Auto => return None,
|
||||||
|
c::ItemAlign::Start => AlignItems::FLEX_START,
|
||||||
|
c::ItemAlign::End => AlignItems::FLEX_END,
|
||||||
|
c::ItemAlign::Center => AlignItems::CENTER,
|
||||||
|
c::ItemAlign::Stretch => AlignItems::STRETCH,
|
||||||
|
c::ItemAlign::Baseline => AlignItems::BASELINE,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn content(align: &c::ContentAlign, auto: AlignContent) -> AlignContent {
|
||||||
|
match align {
|
||||||
|
c::ContentAlign::Auto => auto,
|
||||||
|
c::ContentAlign::Start => AlignContent::FLEX_START,
|
||||||
|
c::ContentAlign::End => AlignContent::FLEX_END,
|
||||||
|
c::ContentAlign::Center => AlignContent::CENTER,
|
||||||
|
c::ContentAlign::Stretch => AlignContent::STRETCH,
|
||||||
|
c::ContentAlign::SpaceBetween => AlignContent::SPACE_BETWEEN,
|
||||||
|
c::ContentAlign::SpaceAround => AlignContent::SPACE_AROUND,
|
||||||
|
c::ContentAlign::SpaceEvenly => AlignContent::SPACE_EVENLY,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The Taffy style of a Box. `dev` converts Px lengths to the solver's device units; the slots that were not legal are named in the second value.
|
||||||
|
/// `main` is the main axis of the flex container this box is a child of: a flex basis runs along
|
||||||
|
/// its parent's main axis, not the box's own.
|
||||||
|
pub(super) fn box_style(s: &c::BoxStyle, paint: &c::Paint, dev: Device, main: Axis) -> (Style, Invalid) {
|
||||||
|
let c::BoxStyle {
|
||||||
|
display,
|
||||||
|
direction,
|
||||||
|
wrap,
|
||||||
|
gap,
|
||||||
|
padding,
|
||||||
|
margin,
|
||||||
|
size,
|
||||||
|
min_size,
|
||||||
|
max_size,
|
||||||
|
position,
|
||||||
|
inset,
|
||||||
|
overflow,
|
||||||
|
align_items,
|
||||||
|
align_self,
|
||||||
|
align_content,
|
||||||
|
justify_content,
|
||||||
|
grow,
|
||||||
|
shrink,
|
||||||
|
basis,
|
||||||
|
grid_columns,
|
||||||
|
grid_rows,
|
||||||
|
} = s;
|
||||||
|
let mut slots = Slots { dev, invalid: Vec::new() };
|
||||||
|
// A border is one width on four sides: across (left, right) and down (top, bottom) it
|
||||||
|
// converts at its own axis.
|
||||||
|
let (border_x, border_y) = match &paint.border {
|
||||||
|
None => (LengthPercentage::ZERO, LengthPercentage::ZERO),
|
||||||
|
Some(b) => {
|
||||||
|
let side = |axis| number(b.width, false).map(|v| dev.border(v, axis)).filter(|v| v.abs() <= MAX_DEVICE);
|
||||||
|
let across = slots.take("border", side(Axis::X), 0.0);
|
||||||
|
let down = side(Axis::Y).unwrap_or(0.0);
|
||||||
|
(LengthPercentage::length(across), LengthPercentage::length(down))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let overflow = match overflow {
|
||||||
|
c::Overflow::Visible => TOverflow::Visible,
|
||||||
|
c::Overflow::Clip => TOverflow::Clip,
|
||||||
|
c::Overflow::Scroll => TOverflow::Scroll,
|
||||||
|
};
|
||||||
|
let gap = {
|
||||||
|
let width = slots.take("gap", lp(&gap.width, dev, Axis::X), LengthPercentage::ZERO);
|
||||||
|
let height = slots.take("gap", lp(&gap.height, dev, Axis::Y), LengthPercentage::ZERO);
|
||||||
|
Size { width, height }
|
||||||
|
};
|
||||||
|
let style = Style {
|
||||||
|
display: match display {
|
||||||
|
c::Display::Flex => TDisplay::Flex,
|
||||||
|
c::Display::Grid => TDisplay::Grid,
|
||||||
|
c::Display::Block => TDisplay::Block,
|
||||||
|
},
|
||||||
|
flex_direction: match direction {
|
||||||
|
c::Direction::Row => FlexDirection::Row,
|
||||||
|
c::Direction::Column => FlexDirection::Column,
|
||||||
|
c::Direction::RowReverse => FlexDirection::RowReverse,
|
||||||
|
c::Direction::ColumnReverse => FlexDirection::ColumnReverse,
|
||||||
|
},
|
||||||
|
flex_wrap: match wrap {
|
||||||
|
c::Wrap::NoWrap => FlexWrap::NoWrap,
|
||||||
|
c::Wrap::Wrap => FlexWrap::Wrap,
|
||||||
|
c::Wrap::WrapReverse => FlexWrap::WrapReverse,
|
||||||
|
},
|
||||||
|
gap,
|
||||||
|
padding: slots.edges_lp("padding", padding),
|
||||||
|
border: Rect { left: border_x, right: border_x, top: border_y, bottom: border_y },
|
||||||
|
margin: slots.edges_lpa("margin", margin, true, LengthPercentageAuto::ZERO),
|
||||||
|
size: slots.size2("size", size),
|
||||||
|
min_size: slots.size2_lpa("min_size", min_size),
|
||||||
|
max_size: slots.size2_lpa("max_size", max_size),
|
||||||
|
position: match position {
|
||||||
|
c::Position::Relative => TPosition::Relative,
|
||||||
|
c::Position::Absolute => TPosition::Absolute,
|
||||||
|
},
|
||||||
|
inset: slots.edges_lpa("inset", inset, true, LengthPercentageAuto::auto()),
|
||||||
|
overflow: Point { x: overflow, y: overflow },
|
||||||
|
scrollbar_width: 0.0,
|
||||||
|
align_items: item(align_items).unwrap_or(AlignItems::STRETCH),
|
||||||
|
align_self: item(align_self),
|
||||||
|
align_content: content(align_content, AlignContent::STRETCH),
|
||||||
|
justify_content: content(justify_content, AlignContent::FLEX_START),
|
||||||
|
flex_grow: slots.weight("grow", *grow, 0.0),
|
||||||
|
flex_shrink: slots.weight("shrink", *shrink, 1.0),
|
||||||
|
flex_basis: {
|
||||||
|
let basis = basis_dim(basis, dev, main);
|
||||||
|
slots.take("basis", basis, Dimension::auto())
|
||||||
|
},
|
||||||
|
grid_template_columns: slots.tracks("grid_columns", Axis::X, grid_columns).into_iter().collect(),
|
||||||
|
grid_template_rows: slots.tracks("grid_rows", Axis::Y, grid_rows).into_iter().collect(),
|
||||||
|
..Style::default()
|
||||||
|
};
|
||||||
|
(style, slots.invalid)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An Embed's style: exactly its declared size, never shrunk.
|
||||||
|
pub(super) fn embed_style(width: f64, height: f64, dev: Device) -> (Style, Invalid) {
|
||||||
|
let mut slots = Slots { dev, invalid: Vec::new() };
|
||||||
|
let side = |slots: &mut Slots, value: f64, axis: Axis| {
|
||||||
|
let v = slots.take("size", length(&c::Scalar { value }, dev, axis, false), 0.0);
|
||||||
|
(Dimension::length(v), LengthPercentageAuto::length(v))
|
||||||
|
};
|
||||||
|
let (w, wa) = side(&mut slots, width, Axis::X);
|
||||||
|
let (h, ha) = side(&mut slots, height, Axis::Y);
|
||||||
|
let style = Style {
|
||||||
|
size: Size { width: w, height: h },
|
||||||
|
min_size: Size { width: wa, height: ha },
|
||||||
|
max_size: Size { width: wa, height: ha },
|
||||||
|
flex_shrink: 0.0,
|
||||||
|
..Style::default()
|
||||||
|
};
|
||||||
|
(style, slots.invalid)
|
||||||
|
}
|
||||||
389
crates/thing-core/src/layout/tree.rs
Normal file
389
crates/thing-core/src/layout/tree.rs
Normal file
|
|
@ -0,0 +1,389 @@
|
||||||
|
//! The walk: a `BoundTree` becomes a Taffy tree, one Taffy node per laid node, Repeats spliced.
|
||||||
|
|
||||||
|
use taffy::{Style, TaffyTree};
|
||||||
|
use thing_contract::{Direction, Node, NodeId, Overflow, OverlayNode};
|
||||||
|
|
||||||
|
use super::ControlForm;
|
||||||
|
use super::measure::{Axis, Device, Leaf, MAX_DEVICE, intrinsic_ratio};
|
||||||
|
use super::style::{Invalid, box_style, embed_style};
|
||||||
|
use crate::bind::{Bound, BoundTree, Field};
|
||||||
|
use crate::diagnostic::{Code, Diagnostic};
|
||||||
|
use crate::resolve::grow;
|
||||||
|
|
||||||
|
static ABSENT: Bound = Bound::Absent;
|
||||||
|
|
||||||
|
/// One laid node, in document order. `parent` is the entry of the nearest laid ancestor.
|
||||||
|
pub(super) struct Entry<'a> {
|
||||||
|
pub(super) id: &'a NodeId,
|
||||||
|
pub(super) node: taffy::NodeId,
|
||||||
|
pub(super) parent: Option<usize>,
|
||||||
|
pub(super) clip: bool,
|
||||||
|
pub(super) scroll: bool,
|
||||||
|
/// A control (Button, TextInput, Select, Toggle): its form and content box are published.
|
||||||
|
pub(super) control: Option<Control>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What `solve` needs to state a control: whether layout reserves it an inset (every control but a
|
||||||
|
/// Pixels Button) and, in Cells, the content node inside its shell whose children are placed from
|
||||||
|
/// the inset origin.
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub(super) struct Control {
|
||||||
|
pub(super) inner: Option<taffy::NodeId>,
|
||||||
|
pub(super) inset: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) struct Built<'a> {
|
||||||
|
pub(super) taffy: TaffyTree<usize>,
|
||||||
|
pub(super) root: taffy::NodeId,
|
||||||
|
pub(super) entries: Vec<Entry<'a>>,
|
||||||
|
/// The Taffy context of a measured leaf is its index here.
|
||||||
|
pub(super) leaves: Vec<Leaf<'a>>,
|
||||||
|
pub(super) diagnostics: Vec<Diagnostic>,
|
||||||
|
/// The visible Overlays met in flow, in document order, for the overlay pass.
|
||||||
|
pub(super) overlays: Vec<&'a OverlayNode>,
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Builder<'a, 'm> {
|
||||||
|
tree: &'a BoundTree,
|
||||||
|
surface: String,
|
||||||
|
dev: Device,
|
||||||
|
measure: &'m mut dyn super::Measure,
|
||||||
|
taffy: TaffyTree<usize>,
|
||||||
|
entries: Vec<Entry<'a>>,
|
||||||
|
leaves: Vec<Leaf<'a>>,
|
||||||
|
diagnostics: Vec<Diagnostic>,
|
||||||
|
overlays: Vec<&'a OverlayNode>,
|
||||||
|
/// The main axis of the container whose children are being visited: the axis a child's flex
|
||||||
|
/// basis runs along. The viewport is a block, whose children take no basis; across stands.
|
||||||
|
main: Axis,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the Taffy tree is rooted at: the viewport holding the document root, or one Overlay.
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub(super) enum Top<'a> {
|
||||||
|
Document,
|
||||||
|
Overlay(&'a OverlayNode),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Build one Taffy tree of `size` device px. The document's tree is a block container (the
|
||||||
|
/// viewport) the root flows in, so a root with an auto width fills it and a Repeat at the root has
|
||||||
|
/// a parent to splice into. An Overlay's tree is the Overlay itself, the first entry: a container
|
||||||
|
/// of Taffy's default style the anchor's size, so its children are laid against the anchor.
|
||||||
|
pub(super) fn build<'a>(
|
||||||
|
tree: &'a BoundTree,
|
||||||
|
dev: Device,
|
||||||
|
top: Top<'a>,
|
||||||
|
size: (f32, f32),
|
||||||
|
measure: &mut dyn super::Measure,
|
||||||
|
) -> Built<'a> {
|
||||||
|
let document = tree.resolved().document();
|
||||||
|
let mut builder = Builder {
|
||||||
|
tree,
|
||||||
|
surface: document.record_key(),
|
||||||
|
dev,
|
||||||
|
measure,
|
||||||
|
taffy: TaffyTree::new(),
|
||||||
|
entries: Vec::new(),
|
||||||
|
leaves: Vec::new(),
|
||||||
|
diagnostics: Vec::new(),
|
||||||
|
overlays: Vec::new(),
|
||||||
|
main: Axis::X,
|
||||||
|
};
|
||||||
|
let mut kids = Vec::new();
|
||||||
|
let mut style = Style {
|
||||||
|
size: taffy::Size { width: taffy::Dimension::length(size.0), height: taffy::Dimension::length(size.1) },
|
||||||
|
..Style::default()
|
||||||
|
};
|
||||||
|
let overlay = match top {
|
||||||
|
Top::Document => {
|
||||||
|
builder.visit(&document.root, None, &mut kids);
|
||||||
|
style.display = taffy::Display::Block;
|
||||||
|
style.position = taffy::Position::Relative;
|
||||||
|
None
|
||||||
|
}
|
||||||
|
Top::Overlay(overlay) => {
|
||||||
|
let index = builder.entry(&overlay.common.id, None, &Overflow::Visible);
|
||||||
|
for child in &overlay.children {
|
||||||
|
builder.visit(child, Some(index), &mut kids);
|
||||||
|
}
|
||||||
|
Some(index)
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let root = builder.taffy.new_with_children(style, &kids).expect("taffy: insert");
|
||||||
|
if let Some(index) = overlay {
|
||||||
|
builder.entries[index].node = root;
|
||||||
|
}
|
||||||
|
Built {
|
||||||
|
taffy: builder.taffy,
|
||||||
|
root,
|
||||||
|
entries: builder.entries,
|
||||||
|
leaves: builder.leaves,
|
||||||
|
diagnostics: builder.diagnostics,
|
||||||
|
overlays: builder.overlays,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Builder<'a, '_> {
|
||||||
|
/// The shell of a Cells control: a grid of three rows (an edge row of up to one row above and
|
||||||
|
/// below, the content row between) one cell in on each side, the inset rule's numbers
|
||||||
|
/// (`Device::inset`). The content node takes the middle row, at least its children's height of it (one row if it has none). The edge
|
||||||
|
/// rows give way first, so the shell lays anywhere from one row up and the form is read off the
|
||||||
|
/// height it ends with (`Device::form`).
|
||||||
|
fn shell(&mut self, content: taffy::NodeId) -> taffy::NodeId {
|
||||||
|
use taffy::style_helpers::{auto, length, line, minmax};
|
||||||
|
let (across, down) = self.dev.inset(ControlForm::Bordered, f32::INFINITY, f32::INFINITY);
|
||||||
|
let mut seat = self.taffy.style(content).expect("taffy: node is in the tree").clone();
|
||||||
|
// A content node with children is never laid shorter than they are (its automatic minimum),
|
||||||
|
// so the row the form reads is the content's own height; a leaf or an empty Button holds one row.
|
||||||
|
if self.taffy.children(content).expect("taffy: node is in the tree").is_empty() {
|
||||||
|
seat.min_size.height = taffy::LengthPercentageAuto::length(1.0);
|
||||||
|
}
|
||||||
|
seat.grid_row = taffy::Line { start: line(2), end: auto() };
|
||||||
|
self.taffy.set_style(content, seat).expect("taffy: style");
|
||||||
|
let edge = || -> taffy::GridTemplateComponent<String> { minmax::<taffy::TrackSizingFunction>(length(0.0), length(down)).into() };
|
||||||
|
let content_row: taffy::GridTemplateComponent<String> = minmax::<taffy::TrackSizingFunction>(auto(), auto()).into();
|
||||||
|
let style = Style {
|
||||||
|
display: taffy::Display::Grid,
|
||||||
|
grid_template_rows: vec![edge(), content_row, edge()],
|
||||||
|
padding: taffy::Rect {
|
||||||
|
left: taffy::LengthPercentage::length(across),
|
||||||
|
right: taffy::LengthPercentage::length(across),
|
||||||
|
top: taffy::LengthPercentage::length(0.0),
|
||||||
|
bottom: taffy::LengthPercentage::length(0.0),
|
||||||
|
},
|
||||||
|
..Style::default()
|
||||||
|
};
|
||||||
|
self.taffy.new_with_children(style, &[content]).expect("taffy: insert")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hidden(&self, id: &NodeId) -> bool {
|
||||||
|
matches!(self.tree.value(id, Field::Visible), Some(Bound::Bool(false)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn value(&self, id: &NodeId, field: Field) -> &'a Bound {
|
||||||
|
self.tree.value(id, field).unwrap_or(&ABSENT)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn report(&mut self, id: &NodeId, invalid: Invalid) {
|
||||||
|
for field in invalid {
|
||||||
|
self.diagnostics.push(Diagnostic {
|
||||||
|
code: Code::StyleValueInvalid,
|
||||||
|
surface: self.surface.clone(),
|
||||||
|
node: Some(id.clone()),
|
||||||
|
detail: field.to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn entry(&mut self, id: &'a NodeId, parent: Option<usize>, overflow: &Overflow) -> usize {
|
||||||
|
let clip = !matches!(overflow, Overflow::Visible);
|
||||||
|
let scroll = matches!(overflow, Overflow::Scroll);
|
||||||
|
self.entries.push(Entry { id, node: taffy::NodeId::from(0u64), parent, clip, scroll, control: None });
|
||||||
|
self.entries.len() - 1
|
||||||
|
}
|
||||||
|
|
||||||
|
fn leaf(&mut self, id: &'a NodeId, parent: Option<usize>, leaf: Leaf<'a>, out: &mut Vec<taffy::NodeId>) {
|
||||||
|
let mut style = Style::default();
|
||||||
|
if matches!(leaf, Leaf::Image { .. }) {
|
||||||
|
// A stretched image keeps its shape: the ratio is what the measure says it is unconstrained.
|
||||||
|
// Whatever its ratio derives, a side of the image stays within the length bound.
|
||||||
|
let bound = taffy::LengthPercentageAuto::length(MAX_DEVICE);
|
||||||
|
style.max_size = taffy::Size { width: bound, height: bound };
|
||||||
|
// An invalid measure leaves the image unconstrained (no ratio, not replaced) and is named.
|
||||||
|
match intrinsic_ratio(self.measure, &leaf, self.dev) {
|
||||||
|
Ok(ratio) => {
|
||||||
|
style.item_is_replaced = true;
|
||||||
|
style.aspect_ratio = ratio;
|
||||||
|
}
|
||||||
|
Err(()) => self.report(id, vec!["measure"]),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let control = matches!(leaf, Leaf::TextInput { .. } | Leaf::Toggle { .. } | Leaf::Select { .. });
|
||||||
|
let index = self.entry(id, parent, &Overflow::Visible);
|
||||||
|
let context = self.leaves.len();
|
||||||
|
self.leaves.push(leaf);
|
||||||
|
let mut node = self.taffy.new_leaf_with_context(style, context).expect("taffy: insert");
|
||||||
|
if control {
|
||||||
|
// In Cells the leaf sits in its shell, which is the control's laid node.
|
||||||
|
let inner = self.dev.cells().then_some(node);
|
||||||
|
if inner.is_some() {
|
||||||
|
node = self.shell(node);
|
||||||
|
}
|
||||||
|
self.entries[index].control = Some(Control { inner, inset: true });
|
||||||
|
}
|
||||||
|
self.entries[index].node = node;
|
||||||
|
out.push(node);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn container(
|
||||||
|
&mut self,
|
||||||
|
id: &'a NodeId,
|
||||||
|
parent: Option<usize>,
|
||||||
|
style: (Style, Invalid),
|
||||||
|
overflow: &Overflow,
|
||||||
|
main: Axis,
|
||||||
|
children: &'a [Node],
|
||||||
|
out: &mut Vec<taffy::NodeId>,
|
||||||
|
) {
|
||||||
|
let (index, node) = self.contain(id, parent, style, overflow, main, children);
|
||||||
|
self.entries[index].node = node;
|
||||||
|
out.push(node);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The entry and Taffy node of a container, its children visited; the caller seats the node.
|
||||||
|
fn contain(
|
||||||
|
&mut self,
|
||||||
|
id: &'a NodeId,
|
||||||
|
parent: Option<usize>,
|
||||||
|
(style, invalid): (Style, Invalid),
|
||||||
|
overflow: &Overflow,
|
||||||
|
main: Axis,
|
||||||
|
children: &'a [Node],
|
||||||
|
) -> (usize, taffy::NodeId) {
|
||||||
|
self.report(id, invalid);
|
||||||
|
let index = self.entry(id, parent, overflow);
|
||||||
|
let mut kids = Vec::new();
|
||||||
|
let outer = std::mem::replace(&mut self.main, main);
|
||||||
|
for child in children {
|
||||||
|
self.visit(child, Some(index), &mut kids);
|
||||||
|
}
|
||||||
|
self.main = outer;
|
||||||
|
(index, self.taffy.new_with_children(style, &kids).expect("taffy: insert"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Append the Taffy nodes `node` contributes to its parent's children: one, none (hidden,
|
||||||
|
/// Overlay, a Repeat with no instances) or one per Repeat instance.
|
||||||
|
fn visit(&mut self, node: &'a Node, parent: Option<usize>, out: &mut Vec<taffy::NodeId>) {
|
||||||
|
grow(|| match node {
|
||||||
|
Node::Box(b) => {
|
||||||
|
if !self.hidden(&b.common.id) {
|
||||||
|
let style = box_style(&b.style, &b.paint, self.dev, self.main);
|
||||||
|
let main = match b.style.direction {
|
||||||
|
Direction::Row | Direction::RowReverse => Axis::X,
|
||||||
|
Direction::Column | Direction::ColumnReverse => Axis::Y,
|
||||||
|
};
|
||||||
|
self.container(&b.common.id, parent, style, &b.style.overflow, main, &b.children, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Node::Button(b) => {
|
||||||
|
if !self.hidden(&b.common.id) {
|
||||||
|
// In Cells the Button is a shell (`Builder::shell`) around a row of its content, the
|
||||||
|
// items centred in it, so a content-sized Button's box includes its border rows and
|
||||||
|
// a short one squeezes to one compact row. Pixels: render draws the chrome behind
|
||||||
|
// the content and no inset applies.
|
||||||
|
if self.dev.cells() {
|
||||||
|
let row = Style { align_items: taffy::AlignItems::CENTER, ..Style::default() };
|
||||||
|
let (index, inner) = self.contain(&b.common.id, parent, (row, Vec::new()), &Overflow::Visible, Axis::X, &b.content);
|
||||||
|
let shell = self.shell(inner);
|
||||||
|
self.entries[index].node = shell;
|
||||||
|
self.entries[index].control = Some(Control { inner: Some(inner), inset: true });
|
||||||
|
out.push(shell);
|
||||||
|
} else {
|
||||||
|
let index = self.entries.len();
|
||||||
|
self.container(&b.common.id, parent, (Style::default(), Vec::new()), &Overflow::Visible, Axis::X, &b.content, out);
|
||||||
|
self.entries[index].control = Some(Control { inner: None, inset: false });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A Repeat has no box: its instances are its parent's children, in instance order.
|
||||||
|
Node::Repeat(r) => {
|
||||||
|
if !self.hidden(&r.common.id) {
|
||||||
|
for instance in self.tree.instances(&r.common.id) {
|
||||||
|
self.visit(&instance.root, parent, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// An Overlay is out of flow: nothing here; the overlay pass lays it out against its anchor.
|
||||||
|
Node::Overlay(o) => {
|
||||||
|
if !self.hidden(&o.common.id) {
|
||||||
|
self.overlays.push(o);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A Use that stayed is resolve's placeholder (beside its diagnostic): a childless leaf
|
||||||
|
// that keeps its place so render can draw the error. A Slot never survives resolve.
|
||||||
|
Node::Use(u) => {
|
||||||
|
if !self.hidden(&u.common.id) {
|
||||||
|
let index = self.entry(&u.common.id, parent, &Overflow::Visible);
|
||||||
|
let (width, height) = self.dev.placeholder();
|
||||||
|
let least = taffy::Size { width: taffy::LengthPercentageAuto::length(width), height: taffy::LengthPercentageAuto::length(height) };
|
||||||
|
let style = Style { min_size: least, ..Style::default() };
|
||||||
|
let id = self.taffy.new_leaf(style).expect("taffy: insert");
|
||||||
|
self.entries[index].node = id;
|
||||||
|
out.push(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Node::Slot(_) => debug_assert!(false, "resolve expands Slot"),
|
||||||
|
Node::Embed(e) => {
|
||||||
|
if !self.hidden(&e.common.id) {
|
||||||
|
let (style, invalid) = embed_style(e.width, e.height, self.dev);
|
||||||
|
self.report(&e.common.id, invalid);
|
||||||
|
let index = self.entry(&e.common.id, parent, &Overflow::Visible);
|
||||||
|
let id = self.taffy.new_leaf(style).expect("taffy: insert");
|
||||||
|
self.entries[index].node = id;
|
||||||
|
out.push(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Node::Text(n) => {
|
||||||
|
let id = &n.common.id;
|
||||||
|
if !self.hidden(id) {
|
||||||
|
let leaf = Leaf::Text {
|
||||||
|
node: id,
|
||||||
|
content: self.value(id, Field::Content),
|
||||||
|
style_token: &n.style_token,
|
||||||
|
wrap: n.wrap,
|
||||||
|
max_lines: n.max_lines.map(|lines| lines.get().max(0) as u32),
|
||||||
|
};
|
||||||
|
self.leaf(id, parent, leaf, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Node::TextInput(n) => {
|
||||||
|
let id = &n.common.id;
|
||||||
|
if !self.hidden(id) {
|
||||||
|
let leaf = Leaf::TextInput {
|
||||||
|
node: id,
|
||||||
|
multiline: n.multiline,
|
||||||
|
placeholder: self.value(id, Field::Placeholder),
|
||||||
|
value: self.value(id, Field::Initial),
|
||||||
|
};
|
||||||
|
self.leaf(id, parent, leaf, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Node::Toggle(n) => {
|
||||||
|
if !self.hidden(&n.common.id) {
|
||||||
|
self.leaf(&n.common.id, parent, Leaf::Toggle { node: &n.common.id }, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Node::Slider(n) => {
|
||||||
|
if !self.hidden(&n.common.id) {
|
||||||
|
self.leaf(&n.common.id, parent, Leaf::Slider { node: &n.common.id }, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Node::Select(n) => {
|
||||||
|
let id = &n.common.id;
|
||||||
|
if !self.hidden(id) {
|
||||||
|
self.leaf(id, parent, Leaf::Select { node: id, selected: self.value(id, Field::Selected) }, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Node::Image(n) => {
|
||||||
|
if !self.hidden(&n.common.id) {
|
||||||
|
let leaf = Leaf::Image { node: &n.common.id, asset: self.value(&n.common.id, Field::Asset) };
|
||||||
|
self.leaf(&n.common.id, parent, leaf, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Node::Plot(n) => {
|
||||||
|
if !self.hidden(&n.common.id) {
|
||||||
|
// A plot declares no size: layout gives it the default object size.
|
||||||
|
let (width, height) = self.dev.plot();
|
||||||
|
let style = Style {
|
||||||
|
size: taffy::Size { width: taffy::Dimension::length(width), height: taffy::Dimension::length(height) },
|
||||||
|
..Style::default()
|
||||||
|
};
|
||||||
|
let index = self.entry(&n.common.id, parent, &Overflow::Visible);
|
||||||
|
let id = self.taffy.new_leaf(style).expect("taffy: insert");
|
||||||
|
self.entries[index].node = id;
|
||||||
|
out.push(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
17
crates/thing-core/src/lib.rs
Normal file
17
crates/thing-core/src/lib.rs
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
//! Thing's core: a function of documents, state, input and time. It touches the world only
|
||||||
|
//! through ports; it reads no clock, spawns nothing and awaits nothing.
|
||||||
|
|
||||||
|
pub mod bind;
|
||||||
|
pub mod command;
|
||||||
|
pub mod diagnostic;
|
||||||
|
pub mod frame;
|
||||||
|
pub mod input;
|
||||||
|
pub mod layout;
|
||||||
|
pub mod port;
|
||||||
|
pub mod render;
|
||||||
|
pub mod resolve;
|
||||||
|
pub mod text;
|
||||||
|
pub mod theme;
|
||||||
|
pub mod time;
|
||||||
|
|
||||||
|
pub use frame::{Config, Core, FrameInput, FrameOutput, Ports};
|
||||||
53
crates/thing-core/src/port/ledger.rs
Normal file
53
crates/thing-core/src/port/ledger.rs
Normal file
|
|
@ -0,0 +1,53 @@
|
||||||
|
//! The one interest ledger: core holds a state interest once however many readers ask for it. A
|
||||||
|
//! reader (the Resolver or the Binder) holds and releases through the ledger, never through the
|
||||||
|
//! port, so one `SubscriptionId` per interest is shared by count and an interest nothing reads
|
||||||
|
//! is unsubscribed.
|
||||||
|
|
||||||
|
use std::collections::{HashMap, HashSet};
|
||||||
|
|
||||||
|
use super::{Interest, StatePort, SubscriptionId};
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
pub struct Ledger {
|
||||||
|
held: HashMap<Interest, (SubscriptionId, usize)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Ledger {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
Self::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One more reader of `interest`; the port is asked only for the first.
|
||||||
|
pub fn hold(&mut self, port: &mut dyn StatePort, interest: &Interest) -> SubscriptionId {
|
||||||
|
let (id, count) = self.held.entry(interest.clone()).or_insert_with(|| (port.subscribe(interest.clone()), 0));
|
||||||
|
*count += 1;
|
||||||
|
*id
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One reader fewer; the port is told when the last goes. Releasing what is not held does nothing.
|
||||||
|
pub fn release(&mut self, port: &mut dyn StatePort, interest: &Interest) {
|
||||||
|
let Some((id, count)) = self.held.get_mut(interest) else { return };
|
||||||
|
*count -= 1;
|
||||||
|
if *count == 0 {
|
||||||
|
let id = *id;
|
||||||
|
self.held.remove(interest);
|
||||||
|
port.unsubscribe(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Move one reader from the interests it held to the ones it holds now: hold only the added,
|
||||||
|
/// release only the removed, touch nothing else.
|
||||||
|
pub fn diff(&mut self, port: &mut dyn StatePort, old: &HashSet<Interest>, new: &HashSet<Interest>) {
|
||||||
|
for added in new.difference(old) {
|
||||||
|
self.hold(port, added);
|
||||||
|
}
|
||||||
|
for removed in old.difference(new) {
|
||||||
|
self.release(port, removed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many readers hold `interest`.
|
||||||
|
pub fn readers(&self, interest: &Interest) -> usize {
|
||||||
|
self.held.get(interest).map_or(0, |(_, count)| *count)
|
||||||
|
}
|
||||||
|
}
|
||||||
152
crates/thing-core/src/port/mod.rs
Normal file
152
crates/thing-core/src/port/mod.rs
Normal file
|
|
@ -0,0 +1,152 @@
|
||||||
|
//! 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>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where core gets the 16 random bytes of an invocation id. Core sets the UUID version and
|
||||||
|
/// variant bits itself, so a source need only be unpredictable; a test source is a script or a counter.
|
||||||
|
pub trait IdSource {
|
||||||
|
fn fill(&mut self, bytes: &mut [u8; 16]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn address(provider: &str, schema: &str, key: &str) -> Address {
|
||||||
|
Address { provider: ProviderId::new(provider), schema: SchemaId::new(schema), key: RecordKey::new(key) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn prefix(provider: &str, schema: &str, key_prefix: &str) -> Prefix {
|
||||||
|
Prefix { provider: ProviderId::new(provider), schema: SchemaId::new(schema), key_prefix: key_prefix.into() }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_prefix_matches_provider_schema_and_key_prefix_together() {
|
||||||
|
let under = prefix("p", "s", "row-");
|
||||||
|
assert!(under.matches(&address("p", "s", "row-1")));
|
||||||
|
assert!(under.matches(&address("p", "s", "row-")));
|
||||||
|
assert!(!under.matches(&address("q", "s", "row-1")));
|
||||||
|
assert!(!under.matches(&address("p", "t", "row-1")));
|
||||||
|
assert!(!under.matches(&address("p", "s", "col-1")));
|
||||||
|
assert!(!under.matches(&address("p", "s", "ro")));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_record_interest_matches_only_its_address() {
|
||||||
|
let interest = Interest::Record(address("p", "s", "k"));
|
||||||
|
assert!(interest.matches(&address("p", "s", "k")));
|
||||||
|
assert!(!interest.matches(&address("p", "s", "k2")));
|
||||||
|
assert!(!interest.matches(&address("q", "s", "k")));
|
||||||
|
assert!(Interest::Prefix(prefix("p", "s", "k")).matches(&address("p", "s", "k2")));
|
||||||
|
assert!(!Interest::Prefix(prefix("p", "s", "k")).matches(&address("p", "s", "j")));
|
||||||
|
}
|
||||||
|
}
|
||||||
26
crates/thing-core/src/port/state.rs
Normal file
26
crates/thing-core/src/port/state.rs
Normal file
|
|
@ -0,0 +1,26 @@
|
||||||
|
//! A provider record's value as core sees it. Core holds no bytes and no reader of them: a state
|
||||||
|
//! port implementation decodes a record with its schema's member names (the `thing-state` crate)
|
||||||
|
//! and hands core this tree.
|
||||||
|
|
||||||
|
/// A provider record's value: closed, ordered and named, with no case folding.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub enum StateValue {
|
||||||
|
Nil,
|
||||||
|
Bool(bool),
|
||||||
|
Int(i128),
|
||||||
|
Float(f64),
|
||||||
|
Text(String),
|
||||||
|
Bytes(Vec<u8>),
|
||||||
|
List(Vec<StateValue>),
|
||||||
|
Record(Vec<(String, StateValue)>),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl StateValue {
|
||||||
|
/// The member of a `Record` by exact name; `None` for any other shape or a missing name.
|
||||||
|
pub fn member(&self, name: &str) -> Option<&StateValue> {
|
||||||
|
match self {
|
||||||
|
StateValue::Record(members) => members.iter().find(|(member, _)| member == name).map(|(_, value)| value),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
37
crates/thing-core/src/render/command.rs
Normal file
37
crates/thing-core/src/render/command.rs
Normal file
|
|
@ -0,0 +1,37 @@
|
||||||
|
//! The closed render-command list. Paint order is emission order: nothing carries a stacking value
|
||||||
|
//! or an escape hatch. Coordinates are f32 logical px (Pixels) or cells (Cells), already divided
|
||||||
|
//! by the scale; colours are literals, so a theme token cannot reach a backend by type.
|
||||||
|
|
||||||
|
use thing_contract::Rgba;
|
||||||
|
|
||||||
|
use crate::layout::{Rect, Run};
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub enum RenderCommand {
|
||||||
|
FillRect { rect: Rect, radius: f32, color: Rgba },
|
||||||
|
StrokeRect { rect: Rect, radius: f32, width: f32, color: Rgba },
|
||||||
|
/// One line of text at `origin` (its top-left).
|
||||||
|
Text { origin: (f32, f32), run: Run, color: Rgba },
|
||||||
|
Image { rect: Rect, uri: String, alt: String },
|
||||||
|
ClipPush { rect: Rect, radius: f32 },
|
||||||
|
ClipPop,
|
||||||
|
Polyline { points: Vec<(f32, f32)>, width: f32, color: Rgba },
|
||||||
|
Polygon { points: Vec<(f32, f32)>, color: Rgba },
|
||||||
|
Embed { rect: Rect, slot_kind: String, slot_id: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether every ClipPush has its ClipPop, nested, and no ClipPop comes first.
|
||||||
|
pub fn balanced(commands: &[RenderCommand]) -> bool {
|
||||||
|
let mut open = 0usize;
|
||||||
|
for command in commands {
|
||||||
|
match command {
|
||||||
|
RenderCommand::ClipPush { .. } => open += 1,
|
||||||
|
RenderCommand::ClipPop => match open.checked_sub(1) {
|
||||||
|
Some(rest) => open = rest,
|
||||||
|
None => return false,
|
||||||
|
},
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
open == 0
|
||||||
|
}
|
||||||
187
crates/thing-core/src/render/leaf.rs
Normal file
187
crates/thing-core/src/render/leaf.rs
Normal file
|
|
@ -0,0 +1,187 @@
|
||||||
|
//! The leaves: control chrome, an Image's fit and the missing-asset placeholder. Core alone turns
|
||||||
|
//! fit and control state into geometry; no caret, selection or focus ring (those need edit and
|
||||||
|
//! focus state). Pixels and Cells share the lowering; only the inset and the stroke differ.
|
||||||
|
|
||||||
|
use std::borrow::Cow;
|
||||||
|
|
||||||
|
use thing_contract::{ButtonNode, ImageFit, ImageNode, NodeId, SelectNode, SliderNode, TextInputNode, ToggleNode};
|
||||||
|
|
||||||
|
use super::Painter;
|
||||||
|
use super::command::RenderCommand;
|
||||||
|
use crate::bind::{Bound, Field};
|
||||||
|
use crate::diagnostic::{Code, Diagnostic};
|
||||||
|
use crate::input::drafts::current;
|
||||||
|
use crate::layout::{ControlForm, LaidControl, Measure, Metrics, Rect, TextRequest};
|
||||||
|
|
||||||
|
/// Where an Image lands inside `rect` for an extent of `(w, h)` asset px (1 asset px = 1 logical
|
||||||
|
/// px), and whether it must be clipped to `rect`.
|
||||||
|
fn fitted(fit: &ImageFit, rect: Rect, (w, h): (f32, f32)) -> (Rect, bool) {
|
||||||
|
let scale = match fit {
|
||||||
|
ImageFit::Fill => return (rect, false),
|
||||||
|
ImageFit::Contain => (rect.w / w).min(rect.h / h),
|
||||||
|
ImageFit::Cover => (rect.w / w).max(rect.h / h),
|
||||||
|
ImageFit::Unscaled => 1.0,
|
||||||
|
};
|
||||||
|
let (dw, dh) = (w * scale, h * scale);
|
||||||
|
let dest = Rect { x: rect.x + (rect.w - dw) / 2.0, y: rect.y + (rect.h - dh) / 2.0, w: dw, h: dh };
|
||||||
|
(dest, matches!(fit, ImageFit::Cover | ImageFit::Unscaled))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Painter<'a> {
|
||||||
|
/// What the site shows: its draft over its bound value, the one read every control makes.
|
||||||
|
fn shown(&self, id: &NodeId, field: Field) -> Option<Cow<'a, Bound>> {
|
||||||
|
current(self.tree, self.input.session.drafts, id, field)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flag(&self, id: &NodeId, field: Field) -> Option<bool> {
|
||||||
|
match self.shown(id, field).as_deref() {
|
||||||
|
Some(Bound::Bool(b)) => Some(*b),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn shown_text(&self, id: &NodeId, field: Field) -> Option<String> {
|
||||||
|
match self.shown(id, field).as_deref() {
|
||||||
|
Some(Bound::Text(t)) => Some(t.clone()),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn stroke(&mut self, id: &NodeId, rect: Rect) {
|
||||||
|
let color = self.named(id, "thing.control.border");
|
||||||
|
self.out.commands.push(RenderCommand::StrokeRect { rect, radius: 0.0, width: 1.0, color });
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fill(&mut self, id: &NodeId, rect: Rect, token: &str) {
|
||||||
|
let color = self.named(id, token);
|
||||||
|
self.out.commands.push(RenderCommand::FillRect { rect, radius: 0.0, color });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The lines of `content` the engine breaks at `at.w`, those that end within `room` of the top.
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub(super) fn draw_text(&mut self, id: &NodeId, content: &str, token: &str, wrap: bool, max_lines: Option<u32>, at: Rect, room: f32, text: &mut dyn Measure) {
|
||||||
|
let color = match self.input.theme.text.get(token) {
|
||||||
|
Some(style) => style.color.clone(),
|
||||||
|
None => self.fault(id, token),
|
||||||
|
};
|
||||||
|
let request = TextRequest { node: id, text: content, style_token: token, wrap, max_lines };
|
||||||
|
for line in text.text(&request, at.w).lines.into_iter().filter(|line| line.y + line.height <= room) {
|
||||||
|
self.out.commands.push(RenderCommand::Text { origin: (at.x, at.y + line.y), run: line.run, color: color.clone() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What stands where a leaf's content could not be drawn: a fill and an error stroke.
|
||||||
|
pub(super) fn placeholder(&mut self, id: &NodeId, rect: Rect) {
|
||||||
|
self.fill(id, rect, "thing.placeholder");
|
||||||
|
let color = self.named(id, "thing.error");
|
||||||
|
self.out.commands.push(RenderCommand::StrokeRect { rect, radius: 0.0, width: 1.0, color });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A control's chrome as layout chose its form: `Bordered` is the box stroke; `Compact` is the
|
||||||
|
/// one-row affordance on the first row, whose stroke is the brackets of a one-row stroke.
|
||||||
|
fn chrome(&mut self, id: &NodeId, rect: Rect, form: ControlForm) {
|
||||||
|
match form {
|
||||||
|
ControlForm::Bordered => self.stroke(id, rect),
|
||||||
|
ControlForm::Compact => self.stroke(id, Rect { h: rect.h.min(1.0), ..rect }),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn button(&mut self, n: &ButtonNode, rect: Rect, control: LaidControl) {
|
||||||
|
let id = &n.common.id;
|
||||||
|
let busy = self.input.session.states.is_some_and(|states| states.get(id).busy);
|
||||||
|
let enabled = self.flag(id, Field::Enabled) != Some(false) && !busy;
|
||||||
|
self.fill(id, rect, if enabled { "thing.control.fill" } else { "thing.control.disabled" });
|
||||||
|
self.chrome(id, rect, control.form);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn toggle(&mut self, n: &ToggleNode, rect: Rect, control: LaidControl) {
|
||||||
|
let id = &n.common.id;
|
||||||
|
let LaidControl { form, content } = control;
|
||||||
|
// A compact toggle is its glyph alone, on the one row its form keeps.
|
||||||
|
let inner = match form {
|
||||||
|
ControlForm::Bordered => content,
|
||||||
|
ControlForm::Compact => Rect { h: content.h.min(1.0), ..content },
|
||||||
|
};
|
||||||
|
if form == ControlForm::Bordered {
|
||||||
|
self.chrome(id, rect, form);
|
||||||
|
}
|
||||||
|
let side = inner.h.min(inner.w / 2.0).max(0.0);
|
||||||
|
let checked = self.flag(id, Field::Checked) == Some(true);
|
||||||
|
let x = if checked { inner.x + inner.w - side } else { inner.x };
|
||||||
|
self.fill(id, Rect { x, y: inner.y + (inner.h - side) / 2.0, w: side, h: side }, "thing.control.accent");
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn slider(&mut self, n: &SliderNode, rect: Rect) {
|
||||||
|
let id = &n.common.id;
|
||||||
|
let thickness = if self.input.metrics == Metrics::Cells { rect.h } else { rect.h / 4.0 };
|
||||||
|
self.fill(id, Rect { x: rect.x, y: rect.y + (rect.h - thickness) / 2.0, w: rect.w, h: thickness }, "thing.control.border");
|
||||||
|
let fraction = if n.min.is_finite() && n.max.is_finite() && n.min < n.max {
|
||||||
|
match self.shown(id, Field::Value).as_deref() {
|
||||||
|
Some(Bound::Number(v)) if v.is_finite() => ((v - n.min) / (n.max - n.min)).clamp(0.0, 1.0),
|
||||||
|
_ => 0.0,
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
self.out.diagnostics.push(Diagnostic {
|
||||||
|
code: Code::StyleValueInvalid,
|
||||||
|
surface: self.tree.resolved().document().record_key(),
|
||||||
|
node: Some(id.clone()),
|
||||||
|
detail: "max".to_string(),
|
||||||
|
});
|
||||||
|
0.0
|
||||||
|
};
|
||||||
|
let side = rect.h.min(rect.w).max(0.0);
|
||||||
|
let x = rect.x + (rect.w - side) * fraction as f32;
|
||||||
|
self.fill(id, Rect { x, y: rect.y, w: side, h: side }, "thing.control.accent");
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn select(&mut self, n: &SelectNode, rect: Rect, control: LaidControl, text: &mut dyn Measure) {
|
||||||
|
let id = &n.common.id;
|
||||||
|
let inner = control.content;
|
||||||
|
self.chrome(id, rect, control.form);
|
||||||
|
let Some(value) = self.shown_text(id, Field::Selected) else { return };
|
||||||
|
let tree = self.tree;
|
||||||
|
let label = match tree.value(id, Field::Options) {
|
||||||
|
Some(Bound::Options(options)) => options.iter().find(|o| o.value == value).map_or(value.as_str(), |o| o.label.as_str()),
|
||||||
|
_ => value.as_str(),
|
||||||
|
};
|
||||||
|
self.draw_text(id, label, "thing.text", false, Some(1), inner, inner.h, text);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn text_input(&mut self, n: &TextInputNode, rect: Rect, control: LaidControl, text: &mut dyn Measure) {
|
||||||
|
let id = &n.common.id;
|
||||||
|
let inner = control.content;
|
||||||
|
self.chrome(id, rect, control.form);
|
||||||
|
let (content, token) = match self.shown_text(id, Field::Initial).filter(|t| !t.is_empty()) {
|
||||||
|
Some(initial) => (initial, "thing.text"),
|
||||||
|
None => match self.shown_text(id, Field::Placeholder) {
|
||||||
|
Some(placeholder) => (placeholder, "thing.text.placeholder"),
|
||||||
|
None => return,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
self.draw_text(id, &content, token, n.multiline, if n.multiline { None } else { Some(1) }, inner, inner.h, text);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn image(&mut self, n: &ImageNode, rect: Rect, text: &mut dyn Measure) {
|
||||||
|
let id = &n.common.id;
|
||||||
|
let alt = self.shown_text(id, Field::Alt).unwrap_or_default();
|
||||||
|
let tree = self.tree;
|
||||||
|
let entry = match tree.value(id, Field::Asset) {
|
||||||
|
Some(Bound::Asset(entry)) if entry.width.get() > 0 && entry.height.get() > 0 => entry,
|
||||||
|
_ => {
|
||||||
|
self.placeholder(id, rect);
|
||||||
|
if !alt.is_empty() && rect.w > 0.0 {
|
||||||
|
self.draw_text(id, &alt, "thing.text", true, Some(1), rect, rect.h, text);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let (dest, clipped) = fitted(&n.fit, rect, (entry.width.get() as f32, entry.height.get() as f32));
|
||||||
|
if clipped {
|
||||||
|
self.out.commands.push(RenderCommand::ClipPush { rect, radius: 0.0 });
|
||||||
|
}
|
||||||
|
self.out.commands.push(RenderCommand::Image { rect: dest, uri: entry.uri.clone(), alt });
|
||||||
|
if clipped {
|
||||||
|
self.out.commands.push(RenderCommand::ClipPop);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
336
crates/thing-core/src/render/mod.rs
Normal file
336
crates/thing-core/src/render/mod.rs
Normal file
|
|
@ -0,0 +1,336 @@
|
||||||
|
//! Render: a `BoundTree`, its `LaidTree`, the scroll offsets and a theme become the closed command
|
||||||
|
//! list and the placed geometry hit-test, IME and accessibility read. A pure function: it reads
|
||||||
|
//! no port, no clock and no state, and equal inputs give an equal `Rendered`.
|
||||||
|
//!
|
||||||
|
//! This is the one place device px become logical px (divided by the scale) and scroll offsets
|
||||||
|
//! apply. Paint order is `LaidTree` order, which layout owns; render only looks nodes up.
|
||||||
|
|
||||||
|
mod command;
|
||||||
|
mod leaf;
|
||||||
|
mod plot;
|
||||||
|
mod scroll;
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use thing_contract::{Anchor, BoxNode, ColorRef, Node, NodeId, Rgba};
|
||||||
|
|
||||||
|
pub use command::{RenderCommand, balanced};
|
||||||
|
pub use scroll::{ScrollOffsets, clamp};
|
||||||
|
|
||||||
|
use crate::bind::{Bound, BoundTree, Field};
|
||||||
|
use crate::command::NodeStates;
|
||||||
|
use crate::diagnostic::{Code, Diagnostic};
|
||||||
|
use crate::input::Drafts;
|
||||||
|
use crate::layout::{ControlForm, LaidControl, LaidNode, LaidTree, MAX_DEVICE, Measure, Metrics, Rect};
|
||||||
|
use crate::theme::{Theme, fallback};
|
||||||
|
|
||||||
|
/// What a frame is drawn with. `viewport` is what layout was given (logical px or cells).
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct RenderInput<'a> {
|
||||||
|
pub scale: f32,
|
||||||
|
pub metrics: Metrics,
|
||||||
|
pub viewport: (f32, f32),
|
||||||
|
pub scroll: &'a ScrollOffsets,
|
||||||
|
pub theme: &'a Theme,
|
||||||
|
pub session: Session<'a>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the user has done that the documents and state do not say: the drafts that draw over bound
|
||||||
|
/// values, and the node states (busy, marked) commands derived. `Session::EMPTY` is a surface nobody
|
||||||
|
/// has touched; a frame drawn with it is the frame the bound tree alone gives.
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub struct Session<'a> {
|
||||||
|
pub drafts: Option<&'a Drafts>,
|
||||||
|
pub states: Option<&'a NodeStates>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Session<'static> {
|
||||||
|
pub const EMPTY: Session<'static> = Session { drafts: None, states: None };
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Session<'a> {
|
||||||
|
pub fn new(drafts: &'a Drafts, states: &'a NodeStates) -> Self {
|
||||||
|
Self { drafts: Some(drafts), states: Some(states) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A laid node as it is on screen. `rect` is the scrolled border box in logical px (cells);
|
||||||
|
/// `visible` is `rect` cut by the clips open around it, `None` when nothing of it shows.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct Placed {
|
||||||
|
pub id: NodeId,
|
||||||
|
pub rect: Rect,
|
||||||
|
pub visible: Option<Rect>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The frame: commands in paint order, `placed` in the same order, and the diagnostics of the
|
||||||
|
/// frame (layout's, then render's).
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct Rendered {
|
||||||
|
pub commands: Vec<RenderCommand>,
|
||||||
|
pub placed: Vec<Placed>,
|
||||||
|
pub diagnostics: Vec<Diagnostic>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Device px per logical px: the scale in Pixels when it is finite and positive, else 1; always 1 in
|
||||||
|
/// Cells. The one owner of the rule: render divides by it, and input multiplies by it.
|
||||||
|
pub(crate) fn device_scale(metrics: Metrics, scale: f32) -> f32 {
|
||||||
|
match metrics {
|
||||||
|
Metrics::Pixels if scale.is_finite() && scale > 0.0 => scale,
|
||||||
|
_ => 1.0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn render(tree: &BoundTree, laid: &LaidTree, input: &RenderInput, text: &mut dyn Measure) -> Rendered {
|
||||||
|
let nodes = tree.index();
|
||||||
|
let k = device_scale(input.metrics, input.scale);
|
||||||
|
let mut ids = HashMap::new();
|
||||||
|
for (i, node) in laid.nodes.iter().enumerate() {
|
||||||
|
ids.entry(&node.id).or_insert(i);
|
||||||
|
}
|
||||||
|
let mut painter = Painter {
|
||||||
|
tree,
|
||||||
|
laid,
|
||||||
|
input,
|
||||||
|
nodes,
|
||||||
|
ids,
|
||||||
|
k,
|
||||||
|
shift: Vec::with_capacity(laid.nodes.len()),
|
||||||
|
inner: Vec::with_capacity(laid.nodes.len()),
|
||||||
|
stack: Vec::new(),
|
||||||
|
clips: Vec::new(),
|
||||||
|
out: Rendered { commands: Vec::new(), placed: Vec::new(), diagnostics: laid.diagnostics.clone() },
|
||||||
|
};
|
||||||
|
for i in 0..laid.nodes.len() {
|
||||||
|
painter.enter(i, text);
|
||||||
|
}
|
||||||
|
while let Some(top) = painter.stack.pop() {
|
||||||
|
painter.close(top);
|
||||||
|
}
|
||||||
|
painter.out
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Painter<'a> {
|
||||||
|
tree: &'a BoundTree,
|
||||||
|
laid: &'a LaidTree,
|
||||||
|
input: &'a RenderInput<'a>,
|
||||||
|
nodes: HashMap<&'a NodeId, &'a Node>,
|
||||||
|
ids: HashMap<&'a NodeId, usize>,
|
||||||
|
k: f32,
|
||||||
|
/// Per laid node so far: the device translation it is drawn under, and the one its children
|
||||||
|
/// are drawn under (that minus its own clamped offset).
|
||||||
|
shift: Vec<(f32, f32)>,
|
||||||
|
inner: Vec<(f32, f32)>,
|
||||||
|
/// The open nodes, a chain of ancestors; and the scrolled padding boxes of the open clips.
|
||||||
|
stack: Vec<usize>,
|
||||||
|
clips: Vec<Rect>,
|
||||||
|
out: Rendered,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn meet(a: Rect, b: Rect) -> Option<Rect> {
|
||||||
|
let (x0, y0) = (a.x.max(b.x), a.y.max(b.y));
|
||||||
|
let (x1, y1) = ((a.x + a.w).min(b.x + b.w), (a.y + a.h).min(b.y + b.h));
|
||||||
|
(x1 >= x0 && y1 >= y0).then_some(Rect { x: x0, y: y0, w: x1 - x0, h: y1 - y0 })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether layout states the node a `Compact` control, whose content is clipped to its rect.
|
||||||
|
fn is_compact(node: &LaidNode) -> bool {
|
||||||
|
node.control.is_some_and(|c| c.form == ControlForm::Compact)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn radius(value: f64) -> f32 {
|
||||||
|
let value = value as f32;
|
||||||
|
if value.is_finite() && value > 0.0 { value } else { 0.0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A thumb along one axis: the track starts at `start` and is `track` long, the content reaches
|
||||||
|
/// `max` past it, and the view is `offset` in. Returns the thumb's start and length.
|
||||||
|
fn thumb_span(start: f32, track: f32, max: f32, offset: f32) -> (f32, f32) {
|
||||||
|
let length = track * track / (track + max);
|
||||||
|
(start + (track - length) * offset / max, length)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Painter<'a> {
|
||||||
|
fn logical(&self, rect: Rect, shift: (f32, f32)) -> Rect {
|
||||||
|
let k = self.k;
|
||||||
|
Rect { x: (rect.x + shift.0) / k, y: (rect.y + shift.1) / k, w: rect.w / k, h: rect.h / k }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn fault(&mut self, node: &NodeId, token: &str) -> Rgba {
|
||||||
|
self.out.diagnostics.push(Diagnostic {
|
||||||
|
code: Code::ThemeTokenUnknown,
|
||||||
|
surface: self.tree.resolved().document().record_key(),
|
||||||
|
node: Some(node.clone()),
|
||||||
|
detail: token.to_string(),
|
||||||
|
});
|
||||||
|
fallback()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn color(&mut self, node: &NodeId, color: &ColorRef) -> Rgba {
|
||||||
|
match (self.input.theme.resolve(color), color) {
|
||||||
|
(Some(rgba), _) => rgba,
|
||||||
|
(None, ColorRef::Token(token)) => self.fault(node, &token.name),
|
||||||
|
(None, ColorRef::Rgba(literal)) => literal.clone(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn named(&mut self, node: &NodeId, name: &str) -> Rgba {
|
||||||
|
match self.input.theme.color(name) {
|
||||||
|
Some(rgba) => rgba,
|
||||||
|
None => self.fault(node, name),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The border a Box draws: its colour and width, when it has a legal width.
|
||||||
|
fn border(&self, b: &'a BoxNode) -> Option<(&'a ColorRef, f32)> {
|
||||||
|
let border = b.paint.border.as_ref()?;
|
||||||
|
let width = border.width as f32;
|
||||||
|
(width.is_finite() && width > 0.0 && width * self.k <= MAX_DEVICE).then_some((&border.color, width))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn enter(&mut self, i: usize, text: &mut dyn Measure) {
|
||||||
|
let tree = self.laid;
|
||||||
|
let laid = &tree.nodes[i];
|
||||||
|
let parent = laid.parent.map(|p| p as usize);
|
||||||
|
while let Some(&top) = self.stack.last() {
|
||||||
|
if Some(top) == parent {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
self.stack.pop();
|
||||||
|
self.close(top);
|
||||||
|
}
|
||||||
|
let node = self.nodes.get(&laid.id).copied();
|
||||||
|
let shift = match (parent, node) {
|
||||||
|
(Some(p), _) => self.inner[p],
|
||||||
|
// An overlay root is carried by what its anchor is carried by, never by the anchor's own scroll.
|
||||||
|
(None, Some(Node::Overlay(o))) => match &o.anchor {
|
||||||
|
Anchor::Node(anchor) => match self.ids.get(&anchor.node) {
|
||||||
|
Some(&a) if a < i => self.shift[a],
|
||||||
|
_ => (0.0, 0.0),
|
||||||
|
},
|
||||||
|
Anchor::Viewport => (0.0, 0.0),
|
||||||
|
},
|
||||||
|
(None, _) => (0.0, 0.0),
|
||||||
|
};
|
||||||
|
let own = self.input.scroll.of(laid);
|
||||||
|
self.shift.push(shift);
|
||||||
|
self.inner.push((shift.0 - own.0, shift.1 - own.1));
|
||||||
|
|
||||||
|
let rect = self.logical(laid.rect, shift);
|
||||||
|
let visible = self.clips.iter().try_fold(rect, |seen, clip| meet(seen, *clip));
|
||||||
|
self.out.placed.push(Placed { id: laid.id.clone(), rect, visible });
|
||||||
|
self.stack.push(i);
|
||||||
|
let Some(node) = node else { return };
|
||||||
|
let control = laid.control.map(|c| LaidControl { content: self.logical(c.content, shift), ..c });
|
||||||
|
self.paint(node, rect, control, text);
|
||||||
|
// A fault commands left on the node shows over its own paint, under what is inside it.
|
||||||
|
if self.input.session.states.is_some_and(|states| states.get(&laid.id).mark.is_some()) {
|
||||||
|
let color = self.named(&laid.id, "thing.error");
|
||||||
|
self.out.commands.push(RenderCommand::StrokeRect { rect, radius: 0.0, width: 1.0, color });
|
||||||
|
}
|
||||||
|
if let (Some(padding), Node::Box(b)) = (laid.clip, node) {
|
||||||
|
let clip = self.logical(padding, shift);
|
||||||
|
let border = self.border(b).map_or(0.0, |(_, width)| width);
|
||||||
|
self.out.commands.push(RenderCommand::ClipPush { rect: clip, radius: (radius(b.paint.radius) - border).max(0.0) });
|
||||||
|
self.clips.push(clip);
|
||||||
|
} else if is_compact(laid) {
|
||||||
|
// A Compact control's content may run past its last row: cut it to the rect the form states.
|
||||||
|
self.out.commands.push(RenderCommand::ClipPush { rect, radius: 0.0 });
|
||||||
|
self.clips.push(rect);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn paint(&mut self, node: &'a Node, rect: Rect, control: Option<LaidControl>, text: &mut dyn Measure) {
|
||||||
|
match node {
|
||||||
|
Node::Box(b) => {
|
||||||
|
let id = &b.common.id;
|
||||||
|
if let Some(background) = &b.paint.background {
|
||||||
|
let color = self.color(id, background);
|
||||||
|
self.out.commands.push(RenderCommand::FillRect { rect, radius: radius(b.paint.radius), color });
|
||||||
|
}
|
||||||
|
if let Some((color, width)) = self.border(b) {
|
||||||
|
let color = self.color(id, color);
|
||||||
|
self.out.commands.push(RenderCommand::StrokeRect { rect, radius: radius(b.paint.radius), width, color });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Node::Overlay(o) if o.modal => {
|
||||||
|
let color = self.named(&o.common.id, "thing.scrim");
|
||||||
|
let (w, h) = self.input.viewport;
|
||||||
|
self.out.commands.push(RenderCommand::FillRect { rect: Rect { x: 0.0, y: 0.0, w, h }, radius: 0.0, color });
|
||||||
|
}
|
||||||
|
Node::Embed(e) => {
|
||||||
|
let (slot_kind, slot_id) = (e.slot_kind.clone(), e.slot_id.clone());
|
||||||
|
self.out.commands.push(RenderCommand::Embed { rect, slot_kind, slot_id });
|
||||||
|
}
|
||||||
|
Node::Use(u) => self.placeholder(&u.common.id, rect),
|
||||||
|
Node::Text(n) => {
|
||||||
|
let tree = self.tree;
|
||||||
|
match tree.value(&n.common.id, Field::Content) {
|
||||||
|
Some(Bound::Text(content)) => {
|
||||||
|
let max_lines = n.max_lines.map(|lines| lines.get().max(0) as u32);
|
||||||
|
self.draw_text(&n.common.id, content, &n.style_token, n.wrap, max_lines, rect, f32::INFINITY, text);
|
||||||
|
}
|
||||||
|
Some(Bound::Error(_)) => {
|
||||||
|
let color = self.named(&n.common.id, "thing.error");
|
||||||
|
self.out.commands.push(RenderCommand::StrokeRect { rect, radius: 0.0, width: 1.0, color });
|
||||||
|
}
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A control layout states no form for has nothing to draw as.
|
||||||
|
Node::Button(n) => match control {
|
||||||
|
Some(c) => self.button(n, rect, c),
|
||||||
|
None => self.placeholder(&n.common.id, rect),
|
||||||
|
},
|
||||||
|
Node::Toggle(n) => match control {
|
||||||
|
Some(c) => self.toggle(n, rect, c),
|
||||||
|
None => self.placeholder(&n.common.id, rect),
|
||||||
|
},
|
||||||
|
Node::Slider(n) => self.slider(n, rect),
|
||||||
|
Node::Select(n) => match control {
|
||||||
|
Some(c) => self.select(n, rect, c, text),
|
||||||
|
None => self.placeholder(&n.common.id, rect),
|
||||||
|
},
|
||||||
|
Node::TextInput(n) => match control {
|
||||||
|
Some(c) => self.text_input(n, rect, c, text),
|
||||||
|
None => self.placeholder(&n.common.id, rect),
|
||||||
|
},
|
||||||
|
Node::Image(n) => self.image(n, rect, text),
|
||||||
|
Node::Plot(n) => self.plot(n, rect),
|
||||||
|
Node::Overlay(_) | Node::Repeat(_) | Node::Slot(_) => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Close an open node: its clip, then its scrollbars (which the clip does not cut).
|
||||||
|
fn close(&mut self, i: usize) {
|
||||||
|
let laid = self.laid;
|
||||||
|
let node = &laid.nodes[i];
|
||||||
|
let Some(padding) = node.clip else {
|
||||||
|
if is_compact(node) {
|
||||||
|
self.clips.pop();
|
||||||
|
self.out.commands.push(RenderCommand::ClipPop);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
self.clips.pop();
|
||||||
|
self.out.commands.push(RenderCommand::ClipPop);
|
||||||
|
let Some(max) = node.max_scroll else { return };
|
||||||
|
let offset = self.input.scroll.of(node);
|
||||||
|
let thickness = match self.input.metrics {
|
||||||
|
Metrics::Cells => 1.0,
|
||||||
|
Metrics::Pixels => self.input.theme.scrollbar.max(0.0),
|
||||||
|
} * self.k;
|
||||||
|
let shift = self.shift[i];
|
||||||
|
let thumb = self.named(&node.id, "thing.scrollbar.thumb");
|
||||||
|
if max.1 > 0.0 {
|
||||||
|
let (y, h) = thumb_span(padding.y, padding.h, max.1, offset.1);
|
||||||
|
let rect = self.logical(Rect { x: padding.x + padding.w - thickness, y, w: thickness, h }, shift);
|
||||||
|
self.out.commands.push(RenderCommand::FillRect { rect, radius: 0.0, color: thumb.clone() });
|
||||||
|
}
|
||||||
|
if max.0 > 0.0 {
|
||||||
|
let (x, w) = thumb_span(padding.x, padding.w, max.0, offset.0);
|
||||||
|
let rect = self.logical(Rect { x, y: padding.y + padding.h - thickness, w, h: thickness }, shift);
|
||||||
|
self.out.commands.push(RenderCommand::FillRect { rect, radius: 0.0, color: thumb });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
173
crates/thing-core/src/render/plot.rs
Normal file
173
crates/thing-core/src/render/plot.rs
Normal file
|
|
@ -0,0 +1,173 @@
|
||||||
|
//! A Plot lowered to geometry: the domain, then Polylines, Polygons or FillRects. Pure and
|
||||||
|
//! bounded: a series of N points gives at most N vertices (Line), 2N (Area: each run of m >= 2
|
||||||
|
//! points adds two baseline vertices) or N rects (Bar); a non-finite or unrepresentable (f32) point is skipped with one diagnostic, never drawn.
|
||||||
|
|
||||||
|
use thing_contract::{PlotMark, PlotNode};
|
||||||
|
|
||||||
|
use super::Painter;
|
||||||
|
use super::command::RenderCommand;
|
||||||
|
use crate::bind::{Bound, Field};
|
||||||
|
use crate::diagnostic::{Code, Diagnostic};
|
||||||
|
use crate::layout::Rect;
|
||||||
|
|
||||||
|
/// One axis' domain: an explicit bound that is finite and not crossed by the other end is kept,
|
||||||
|
/// anything else takes the data value and is named; equal ends widen by 1 each way.
|
||||||
|
fn domain(explicit: (Option<f64>, Option<f64>), data: (f64, f64), names: (&'static str, &'static str), invalid: &mut Vec<&'static str>) -> (f64, f64) {
|
||||||
|
let (mut lo, mut hi) = (explicit.0.filter(|v| v.is_finite()), explicit.1.filter(|v| v.is_finite()));
|
||||||
|
if explicit.0.is_some() && lo.is_none() {
|
||||||
|
invalid.push(names.0);
|
||||||
|
}
|
||||||
|
if explicit.1.is_some() && hi.is_none() {
|
||||||
|
invalid.push(names.1);
|
||||||
|
}
|
||||||
|
if let (Some(a), Some(b)) = (lo, hi) {
|
||||||
|
if a > b {
|
||||||
|
invalid.extend([names.0, names.1]);
|
||||||
|
(lo, hi) = (None, None);
|
||||||
|
}
|
||||||
|
} else if let Some(a) = lo {
|
||||||
|
if a > data.1 {
|
||||||
|
invalid.push(names.0);
|
||||||
|
lo = None;
|
||||||
|
}
|
||||||
|
} else if let Some(b) = hi {
|
||||||
|
if b < data.0 {
|
||||||
|
invalid.push(names.1);
|
||||||
|
hi = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let (lo, hi) = (lo.unwrap_or(data.0), hi.unwrap_or(data.1));
|
||||||
|
if lo == hi { (lo - 1.0, hi + 1.0) } else { (lo, hi) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the series lands in `rect`: screen y grows down.
|
||||||
|
struct Frame {
|
||||||
|
rect: Rect,
|
||||||
|
x: (f64, f64),
|
||||||
|
y: (f64, f64),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Frame {
|
||||||
|
/// A point of the series as f32 screen coordinates, `None` when either does not fit an f32.
|
||||||
|
fn at(&self, i: usize, v: f64) -> Option<(f32, f32)> {
|
||||||
|
let tx = halved(i as f64, self.x);
|
||||||
|
let x = (self.rect.x as f64 + tx * self.rect.w as f64) as f32;
|
||||||
|
let y = self.value(v) as f32;
|
||||||
|
(x.is_finite() && y.is_finite()).then_some((x, y))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Screen y of a value: y grows down. Halves keep a span near f64's range from overflowing.
|
||||||
|
fn value(&self, v: f64) -> f64 {
|
||||||
|
self.rect.y as f64 + self.rect.h as f64 - halved(v, self.y) * self.rect.h as f64
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where `v` falls in `(lo, hi)`, 0 to 1, computed on halves so `hi - lo` cannot overflow.
|
||||||
|
fn halved(v: f64, (lo, hi): (f64, f64)) -> f64 {
|
||||||
|
(v / 2.0 - lo / 2.0) / (hi / 2.0 - lo / 2.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Painter<'_> {
|
||||||
|
pub(super) fn plot(&mut self, n: &thing_contract::PlotNode, rect: Rect) {
|
||||||
|
let tree = self.tree;
|
||||||
|
match tree.value(&n.common.id, Field::Series) {
|
||||||
|
Some(Bound::Series(values)) => self.plot_series(n, values, rect),
|
||||||
|
Some(Bound::Error(_)) => self.placeholder(&n.common.id, rect),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A point that was not drawn is said once for the plot, whatever the reason.
|
||||||
|
fn dropped(&mut self, n: &PlotNode) {
|
||||||
|
self.out.diagnostics.push(Diagnostic {
|
||||||
|
code: Code::StyleValueInvalid,
|
||||||
|
surface: self.tree.resolved().document().record_key(),
|
||||||
|
node: Some(n.common.id.clone()),
|
||||||
|
detail: "series".to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn plot_series(&mut self, n: &PlotNode, values: &[f64], rect: Rect) {
|
||||||
|
if values.is_empty() || !(rect.w > 0.0 && rect.h > 0.0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let finite = || values.iter().copied().filter(|v| v.is_finite());
|
||||||
|
let low = finite().fold(f64::INFINITY, f64::min);
|
||||||
|
let high = finite().fold(f64::NEG_INFINITY, f64::max);
|
||||||
|
let data_y = if low <= high { (low, high) } else { (0.0, 0.0) };
|
||||||
|
let mut invalid = Vec::new();
|
||||||
|
let x = domain((n.x_min, n.x_max), (0.0, (values.len() - 1) as f64), ("x_min", "x_max"), &mut invalid);
|
||||||
|
let y = domain((n.y_min, n.y_max), data_y, ("y_min", "y_max"), &mut invalid);
|
||||||
|
for name in invalid {
|
||||||
|
self.out.diagnostics.push(Diagnostic {
|
||||||
|
code: Code::StyleValueInvalid,
|
||||||
|
surface: self.tree.resolved().document().record_key(),
|
||||||
|
node: Some(n.common.id.clone()),
|
||||||
|
detail: name.to_string(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
let frame = Frame { rect, x, y };
|
||||||
|
let color = self.named(&n.common.id, "thing.plot.mark");
|
||||||
|
let width = match self.input.metrics {
|
||||||
|
crate::layout::Metrics::Cells => 1.0,
|
||||||
|
crate::layout::Metrics::Pixels => 2.0,
|
||||||
|
};
|
||||||
|
let base = frame.value(0.0f64.clamp(y.0, y.1));
|
||||||
|
if !(base as f32).is_finite() {
|
||||||
|
self.dropped(n);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let mut shapes = Vec::new();
|
||||||
|
let mut dropped = false;
|
||||||
|
match n.mark {
|
||||||
|
PlotMark::Bar => {
|
||||||
|
let slot = rect.w / values.len() as f32;
|
||||||
|
for (i, v) in values.iter().enumerate() {
|
||||||
|
let top = frame.value(*v);
|
||||||
|
let (y0, y1) = (top.min(base) as f32, top.max(base) as f32);
|
||||||
|
let bar = Rect { x: rect.x + slot * i as f32, y: y0, w: slot, h: y1 - y0 };
|
||||||
|
if v.is_finite() && [bar.x, bar.y, bar.w, bar.h].iter().all(|c| c.is_finite()) {
|
||||||
|
shapes.push(RenderCommand::FillRect { rect: bar, radius: 0.0, color: color.clone() });
|
||||||
|
} else {
|
||||||
|
dropped = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
PlotMark::Line | PlotMark::Area => {
|
||||||
|
let mut run: Vec<(f32, f32)> = Vec::new();
|
||||||
|
let flush = |run: &mut Vec<(f32, f32)>, shapes: &mut Vec<RenderCommand>| {
|
||||||
|
if run.len() >= 2 {
|
||||||
|
let mut points = std::mem::take(run);
|
||||||
|
if n.mark == PlotMark::Area {
|
||||||
|
let (first, last) = (points[0].0, points[points.len() - 1].0);
|
||||||
|
points.extend([(last, base as f32), (first, base as f32)]);
|
||||||
|
shapes.push(RenderCommand::Polygon { points, color: color.clone() });
|
||||||
|
} else {
|
||||||
|
shapes.push(RenderCommand::Polyline { points, width, color: color.clone() });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
run.clear();
|
||||||
|
};
|
||||||
|
for (i, v) in values.iter().enumerate() {
|
||||||
|
match v.is_finite().then(|| frame.at(i, *v)).flatten() {
|
||||||
|
Some(point) => run.push(point),
|
||||||
|
None => {
|
||||||
|
dropped = true;
|
||||||
|
flush(&mut run, &mut shapes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
flush(&mut run, &mut shapes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if dropped {
|
||||||
|
self.dropped(n);
|
||||||
|
}
|
||||||
|
if shapes.is_empty() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.out.commands.push(RenderCommand::ClipPush { rect, radius: 0.0 });
|
||||||
|
self.out.commands.extend(shapes);
|
||||||
|
self.out.commands.push(RenderCommand::ClipPop);
|
||||||
|
}
|
||||||
|
}
|
||||||
38
crates/thing-core/src/render/scroll.rs
Normal file
38
crates/thing-core/src/render/scroll.rs
Normal file
|
|
@ -0,0 +1,38 @@
|
||||||
|
//! Scroll positions: runtime state, never a layout input. Input writes them here and render reads
|
||||||
|
//! them here, both through the one `clamp`.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use thing_contract::NodeId;
|
||||||
|
|
||||||
|
use crate::layout::LaidNode;
|
||||||
|
|
||||||
|
/// `offset` held within `[0, max_scroll]` on each axis; a NaN offset is 0, and an axis that
|
||||||
|
/// cannot scroll holds 0.
|
||||||
|
pub fn clamp(offset: (f32, f32), max_scroll: (f32, f32)) -> (f32, f32) {
|
||||||
|
let axis = |v: f32, max: f32| if v.is_nan() || !(max > 0.0 && max.is_finite()) { 0.0 } else { v.clamp(0.0, max) };
|
||||||
|
(axis(offset.0, max_scroll.0), axis(offset.1, max_scroll.1))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where each scroll node is scrolled to, in device px (Pixels) or cells (Cells), as written.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq)]
|
||||||
|
pub struct ScrollOffsets(HashMap<NodeId, (f32, f32)>);
|
||||||
|
|
||||||
|
impl ScrollOffsets {
|
||||||
|
pub fn set(&mut self, node: NodeId, offset: (f32, f32)) {
|
||||||
|
self.0.insert(node, offset);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get(&self, node: &NodeId) -> Option<(f32, f32)> {
|
||||||
|
self.0.get(node).copied()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The offset a laid node is drawn at: what was written, clamped to what layout says it can
|
||||||
|
/// scroll. A node that does not scroll, or has no offset, has none.
|
||||||
|
pub fn of(&self, node: &LaidNode) -> (f32, f32) {
|
||||||
|
match (self.0.get(&node.id), node.max_scroll) {
|
||||||
|
(Some(offset), Some(max)) => clamp(*offset, max),
|
||||||
|
_ => (0.0, 0.0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
597
crates/thing-core/src/resolve/expand.rs
Normal file
597
crates/thing-core/src/resolve/expand.rs
Normal file
|
|
@ -0,0 +1,597 @@
|
||||||
|
//! The substitution: depth first, order preserving. A surface and a composition body go through
|
||||||
|
//! the same functions; the scope says whether a Param is bound.
|
||||||
|
//!
|
||||||
|
//! Expanded ids: inside the expansion of Use `u`, the body root takes `u`'s id and every other
|
||||||
|
//! body id `b` becomes `u/b`. Arguments are expanded in the caller's scope before the body sees
|
||||||
|
//! them, so a Slot argument's nodes keep the ids they had in the caller.
|
||||||
|
|
||||||
|
use std::collections::{HashMap, HashSet};
|
||||||
|
|
||||||
|
use thing_contract::*;
|
||||||
|
|
||||||
|
use crate::diagnostic::{Code, Diagnostic};
|
||||||
|
use crate::port::{Address, Lookup, Record, StatePort};
|
||||||
|
|
||||||
|
use super::{Limits, std as thing_std, validate};
|
||||||
|
|
||||||
|
/// The deepest input the expander recurses into. This is a stack bound and not the depth rule: the
|
||||||
|
/// rule (`Limits::max_tree_depth`) is judged by validate on the finished tree, where a slot argument
|
||||||
|
/// the body never places does not count. It exists because an in-memory tree from a Rust caller can
|
||||||
|
/// be deeper than any decoded document (CultCache bounds decoded nesting at 256), and recursion
|
||||||
|
/// over it would overflow the stack. The recursion grows its own stack (`super::grow`), so the bound
|
||||||
|
/// holds on any thread.
|
||||||
|
const STACK_BOUND: usize = 1024;
|
||||||
|
|
||||||
|
/// A fault the nearest enclosing Use turns into a placeholder (`Invalid`), or one that ends the
|
||||||
|
/// whole expansion (`Limit`, or `Stack` for input too deep to recurse into).
|
||||||
|
pub(super) enum Fault {
|
||||||
|
Invalid(String),
|
||||||
|
Limit(String),
|
||||||
|
Stack(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
type Res<T> = Result<T, Fault>;
|
||||||
|
|
||||||
|
fn invalid<T>(detail: String) -> Res<T> {
|
||||||
|
Err(Fault::Invalid(detail))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The expansion of one composition body: the Use's id and common, and the finished arguments.
|
||||||
|
struct Scope {
|
||||||
|
use_id: NodeId,
|
||||||
|
root_id: NodeId,
|
||||||
|
use_visible: BoolSource,
|
||||||
|
use_a11y: Option<TextSource>,
|
||||||
|
args: HashMap<String, ArgValue>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) struct Expander<'a> {
|
||||||
|
port: &'a dyn StatePort,
|
||||||
|
limits: &'a Limits,
|
||||||
|
surface: String,
|
||||||
|
provider: &'a ProviderId,
|
||||||
|
commands: HashSet<&'a CommandId>,
|
||||||
|
pub diagnostics: Vec<Diagnostic>,
|
||||||
|
pub reads: HashSet<Address>,
|
||||||
|
nodes: usize,
|
||||||
|
stack: Vec<CompositionRef>,
|
||||||
|
current: Option<NodeId>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn arm_name(value: &ArgValue) -> &'static str {
|
||||||
|
match value {
|
||||||
|
ArgValue::Text(_) => "Text",
|
||||||
|
ArgValue::Number(_) => "Number",
|
||||||
|
ArgValue::Bool(_) => "Bool",
|
||||||
|
ArgValue::Bind(_) => "Bind",
|
||||||
|
ArgValue::Collection(_) => "Collection",
|
||||||
|
ArgValue::Command(_) => "Command",
|
||||||
|
ArgValue::Slot(_) => "Slot",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn kind_name(kind: &ParamKind) -> &'static str {
|
||||||
|
match kind {
|
||||||
|
ParamKind::Text => "Text",
|
||||||
|
ParamKind::Number => "Number",
|
||||||
|
ParamKind::Bool => "Bool",
|
||||||
|
ParamKind::Bind => "Bind",
|
||||||
|
ParamKind::Collection => "Collection",
|
||||||
|
ParamKind::Command => "Command",
|
||||||
|
ParamKind::Slot => "Slot",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wrong_kind<T>(name: &ParamName, value: &ArgValue, position: &str) -> Res<T> {
|
||||||
|
invalid(format!("param '{}' is a {} argument, used as {position}", name.name, arm_name(value)))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<'a> Expander<'a> {
|
||||||
|
pub fn new(document: &'a SurfaceDocument, port: &'a dyn StatePort, limits: &'a Limits) -> Self {
|
||||||
|
Self {
|
||||||
|
port,
|
||||||
|
limits,
|
||||||
|
surface: document.record_key(),
|
||||||
|
provider: &document.provider_id,
|
||||||
|
commands: document.commands.iter().map(|declared| &declared.id).collect(),
|
||||||
|
diagnostics: Vec::new(),
|
||||||
|
reads: HashSet::new(),
|
||||||
|
nodes: 0,
|
||||||
|
stack: Vec::new(),
|
||||||
|
current: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn diag(&mut self, code: Code, node: Option<NodeId>, detail: impl Into<String>) {
|
||||||
|
self.diagnostics.push(Diagnostic { code, surface: self.surface.clone(), node, detail: detail.into() });
|
||||||
|
}
|
||||||
|
|
||||||
|
fn unbound(&mut self, what: &str) {
|
||||||
|
let node = self.current.clone();
|
||||||
|
self.diag(Code::UnboundParam, node, format!("{what} outside a composition"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The surface root: no scope, no Use above it.
|
||||||
|
pub fn root(&mut self, root: &Node) -> Res<Node> {
|
||||||
|
self.node(root, None, 1, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- positions ----------------------------------------------------------------------
|
||||||
|
|
||||||
|
fn id(&self, id: &NodeId, scope: Option<&Scope>) -> NodeId {
|
||||||
|
match scope {
|
||||||
|
None => id.clone(),
|
||||||
|
Some(scope) if *id == scope.root_id => scope.use_id.clone(),
|
||||||
|
Some(scope) => NodeId::new(format!("{}/{}", scope.use_id.as_str(), id.as_str())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fill(&self, provider: &Option<ProviderId>) -> Option<ProviderId> {
|
||||||
|
Some(provider.clone().unwrap_or_else(|| self.provider.clone()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bind(&self, bind: &Bind) -> Bind {
|
||||||
|
let source = match &bind.source {
|
||||||
|
StateSource::Record(state) => StateSource::Record(StateRef {
|
||||||
|
provider: self.fill(&state.provider),
|
||||||
|
schema: state.schema.clone(),
|
||||||
|
key: state.key.clone(),
|
||||||
|
}),
|
||||||
|
StateSource::Item => StateSource::Item,
|
||||||
|
};
|
||||||
|
Bind { source, member: bind.member.clone(), format: bind.format.clone() }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn arg_of<'s>(name: &ParamName, scope: &'s Scope) -> Res<&'s ArgValue> {
|
||||||
|
match scope.args.get(&name.name) {
|
||||||
|
Some(value) => Ok(value),
|
||||||
|
None => invalid(format!("the body names param '{}', which the composition does not declare", name.name)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn text(&mut self, source: &TextSource, scope: Option<&Scope>) -> Res<TextSource> {
|
||||||
|
Ok(match (source, scope) {
|
||||||
|
(TextSource::Literal(_), _) => source.clone(),
|
||||||
|
(TextSource::Bound(bind), _) => TextSource::Bound(self.bind(bind)),
|
||||||
|
(TextSource::Param(name), None) => {
|
||||||
|
self.unbound(&format!("param '{}'", name.name));
|
||||||
|
source.clone()
|
||||||
|
}
|
||||||
|
(TextSource::Param(name), Some(scope)) => match Self::arg_of(name, scope)? {
|
||||||
|
ArgValue::Text(arg) => TextSource::Literal(TextLiteral { value: arg.value.clone() }),
|
||||||
|
ArgValue::Bind(bind) => TextSource::Bound(bind.clone()),
|
||||||
|
other => return wrong_kind(name, other, "text"),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn number(&mut self, source: &NumberSource, scope: Option<&Scope>) -> Res<NumberSource> {
|
||||||
|
Ok(match (source, scope) {
|
||||||
|
(NumberSource::Literal(_), _) => source.clone(),
|
||||||
|
(NumberSource::Bound(bind), _) => NumberSource::Bound(self.bind(bind)),
|
||||||
|
(NumberSource::Param(name), None) => {
|
||||||
|
self.unbound(&format!("param '{}'", name.name));
|
||||||
|
source.clone()
|
||||||
|
}
|
||||||
|
(NumberSource::Param(name), Some(scope)) => match Self::arg_of(name, scope)? {
|
||||||
|
ArgValue::Number(arg) => NumberSource::Literal(NumberLiteral { value: arg.value }),
|
||||||
|
ArgValue::Bind(bind) => NumberSource::Bound(bind.clone()),
|
||||||
|
other => return wrong_kind(name, other, "a number"),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn boolean(&mut self, source: &BoolSource, scope: Option<&Scope>) -> Res<BoolSource> {
|
||||||
|
Ok(match (source, scope) {
|
||||||
|
(BoolSource::Literal(_), _) => source.clone(),
|
||||||
|
(BoolSource::Bound(bind), _) => BoolSource::Bound(self.bind(bind)),
|
||||||
|
(BoolSource::Param(name), None) => {
|
||||||
|
self.unbound(&format!("param '{}'", name.name));
|
||||||
|
source.clone()
|
||||||
|
}
|
||||||
|
(BoolSource::Param(name), Some(scope)) => match Self::arg_of(name, scope)? {
|
||||||
|
ArgValue::Bool(arg) => BoolSource::Literal(BoolLiteral { value: arg.value }),
|
||||||
|
ArgValue::Bind(bind) => BoolSource::Bound(bind.clone()),
|
||||||
|
other => return wrong_kind(name, other, "a bool"),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Substitution only: the form an argument takes, before any position judges it.
|
||||||
|
fn subst_collection(&mut self, source: &CollectionSource, scope: Option<&Scope>) -> Res<CollectionSource> {
|
||||||
|
Ok(match (source, scope) {
|
||||||
|
(CollectionSource::Records(records), _) => CollectionSource::Records(RecordsSource {
|
||||||
|
provider: self.fill(&records.provider),
|
||||||
|
schema: records.schema.clone(),
|
||||||
|
key_prefix: records.key_prefix.clone(),
|
||||||
|
}),
|
||||||
|
(CollectionSource::Member(bind), _) => CollectionSource::Member(self.bind(bind)),
|
||||||
|
(CollectionSource::Param(_), None) => source.clone(),
|
||||||
|
(CollectionSource::Param(name), Some(scope)) => match Self::arg_of(name, scope)? {
|
||||||
|
ArgValue::Collection(arg) => arg.source.clone(),
|
||||||
|
other => return wrong_kind(name, other, "a collection"),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn collection(&mut self, source: &CollectionSource, scope: Option<&Scope>) -> Res<CollectionSource> {
|
||||||
|
let found = self.subst_collection(source, scope)?;
|
||||||
|
if let CollectionSource::Param(name) = &found {
|
||||||
|
self.unbound(&format!("param '{}'", name.name));
|
||||||
|
}
|
||||||
|
Ok(found)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn subst_command(&mut self, command: &CommandRef, scope: Option<&Scope>) -> Res<CommandRef> {
|
||||||
|
Ok(match (command, scope) {
|
||||||
|
(_, None) => command.clone(),
|
||||||
|
(CommandRef::Id(id), Some(_)) => {
|
||||||
|
return invalid(format!(
|
||||||
|
"the body names command '{}'; a composition takes its commands as params",
|
||||||
|
id.id.as_str()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
(CommandRef::Param(name), Some(scope)) => match Self::arg_of(name, scope)? {
|
||||||
|
ArgValue::Command(arg) => arg.command.clone(),
|
||||||
|
other => return wrong_kind(name, other, "a command"),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A command at its final position: declared by the surface, and no Param.
|
||||||
|
fn command(&mut self, command: &CommandRef, scope: Option<&Scope>) -> Res<CommandRef> {
|
||||||
|
let found = self.subst_command(command, scope)?;
|
||||||
|
match &found {
|
||||||
|
CommandRef::Id(id) if !self.commands.contains(&id.id) => {
|
||||||
|
let node = self.current.clone();
|
||||||
|
self.diag(Code::UndeclaredCommand, node, format!("command '{}' is not declared", id.id.as_str()));
|
||||||
|
}
|
||||||
|
CommandRef::Param(name) => self.unbound(&format!("param '{}'", name.name)),
|
||||||
|
CommandRef::Id(_) => {}
|
||||||
|
}
|
||||||
|
Ok(found)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn common(&mut self, common: &NodeCommon, scope: Option<&Scope>, root: bool) -> Res<NodeCommon> {
|
||||||
|
let id = self.id(&common.id, scope);
|
||||||
|
self.current = Some(id.clone());
|
||||||
|
match scope {
|
||||||
|
// A body root is the Use: its id, and its visibility and label unless the body labels it.
|
||||||
|
Some(scope) if root => {
|
||||||
|
if common.visible != BoolSource::Literal(BoolLiteral { value: true }) {
|
||||||
|
return invalid("the body root's visible is not the literal true; visibility is the Use's".into());
|
||||||
|
}
|
||||||
|
let a11y_label = match (&scope.use_a11y, &common.a11y_label) {
|
||||||
|
(Some(label), _) => Some(label.clone()),
|
||||||
|
(None, Some(label)) => Some(self.text(label, Some(scope))?),
|
||||||
|
(None, None) => None,
|
||||||
|
};
|
||||||
|
Ok(NodeCommon { id, visible: scope.use_visible.clone(), a11y_label })
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
let visible = self.boolean(&common.visible, scope)?;
|
||||||
|
let a11y_label = common.a11y_label.as_ref().map(|label| self.text(label, scope)).transpose()?;
|
||||||
|
Ok(NodeCommon { id, visible, a11y_label })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- nodes --------------------------------------------------------------------------
|
||||||
|
|
||||||
|
fn count(&mut self, added: usize) -> Res<()> {
|
||||||
|
self.nodes += added;
|
||||||
|
if self.nodes > self.limits.max_nodes {
|
||||||
|
return Err(Fault::Limit(format!("the expansion passed {} nodes", self.limits.max_nodes)));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A child list. In a composition body a Slot is replaced by the nodes passed for it.
|
||||||
|
fn children(&mut self, list: &[Node], scope: Option<&Scope>, depth: usize) -> Res<Vec<Node>> {
|
||||||
|
let mut out = Vec::with_capacity(list.len());
|
||||||
|
for node in list {
|
||||||
|
match (node, scope) {
|
||||||
|
(Node::Slot(slot), Some(scope)) => match Self::arg_of(&slot.param, scope)? {
|
||||||
|
ArgValue::Slot(arg) => {
|
||||||
|
self.count(arg.nodes.iter().map(validate::size).sum())?;
|
||||||
|
out.extend(arg.nodes.iter().map(clone_deep));
|
||||||
|
}
|
||||||
|
other => return wrong_kind(&slot.param, other, "a slot"),
|
||||||
|
},
|
||||||
|
_ => out.push(self.node(node, scope, depth, false)?),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn node(&mut self, node: &Node, scope: Option<&Scope>, depth: usize, root: bool) -> Res<Node> {
|
||||||
|
super::grow(|| self.node_at(node, scope, depth, root))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn node_at(&mut self, node: &Node, scope: Option<&Scope>, depth: usize, root: bool) -> Res<Node> {
|
||||||
|
if depth > STACK_BOUND {
|
||||||
|
return Err(Fault::Stack(format!("the input nests deeper than {STACK_BOUND} levels")));
|
||||||
|
}
|
||||||
|
self.count(1)?;
|
||||||
|
// Each arm settles its own positions first and its child lists last: a diagnostic names the
|
||||||
|
// node being expanded, and a child list moves `current` on.
|
||||||
|
Ok(match node {
|
||||||
|
Node::Slot(slot) => match scope {
|
||||||
|
Some(_) => {
|
||||||
|
return invalid(format!(
|
||||||
|
"Slot '{}' is not in a child list of the body; a slot stands only in Box.children, \
|
||||||
|
Button.content or Overlay.children",
|
||||||
|
slot.param.name
|
||||||
|
));
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
self.current = None;
|
||||||
|
self.unbound(&format!("Slot '{}'", slot.param.name));
|
||||||
|
node.clone()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Node::Use(used) => self.expand_use(used, scope, depth, root)?,
|
||||||
|
Node::Box(b) => {
|
||||||
|
let common = self.common(&b.common, scope, root)?;
|
||||||
|
let children = self.children(&b.children, scope, depth + 1)?;
|
||||||
|
Node::Box(BoxNode { common, style: b.style.clone(), paint: b.paint.clone(), role: b.role.clone(), children })
|
||||||
|
}
|
||||||
|
Node::Text(t) => {
|
||||||
|
let common = self.common(&t.common, scope, root)?;
|
||||||
|
let content = self.text(&t.content, scope)?;
|
||||||
|
Node::Text(TextNode { common, content, ..t.clone() })
|
||||||
|
}
|
||||||
|
Node::Image(i) => {
|
||||||
|
let common = self.common(&i.common, scope, root)?;
|
||||||
|
let alt = self.text(&i.alt, scope)?;
|
||||||
|
Node::Image(ImageNode { common, alt, ..i.clone() })
|
||||||
|
}
|
||||||
|
Node::Button(b) => {
|
||||||
|
let common = self.common(&b.common, scope, root)?;
|
||||||
|
let on_activate = self.command(&b.on_activate, scope)?;
|
||||||
|
let enabled = self.boolean(&b.enabled, scope)?;
|
||||||
|
let content = self.children(&b.content, scope, depth + 1)?;
|
||||||
|
Node::Button(ButtonNode { common, content, on_activate, enabled })
|
||||||
|
}
|
||||||
|
Node::Toggle(t) => {
|
||||||
|
let common = self.common(&t.common, scope, root)?;
|
||||||
|
let checked = self.boolean(&t.checked, scope)?;
|
||||||
|
let on_change = self.command(&t.on_change, scope)?;
|
||||||
|
Node::Toggle(ToggleNode { common, checked, on_change })
|
||||||
|
}
|
||||||
|
Node::Slider(s) => {
|
||||||
|
let common = self.common(&s.common, scope, root)?;
|
||||||
|
let value = self.number(&s.value, scope)?;
|
||||||
|
let commit = self.command(&s.commit, scope)?;
|
||||||
|
Node::Slider(SliderNode { common, value, commit, ..s.clone() })
|
||||||
|
}
|
||||||
|
Node::TextInput(t) => {
|
||||||
|
let common = self.common(&t.common, scope, root)?;
|
||||||
|
let placeholder = self.text(&t.placeholder, scope)?;
|
||||||
|
let initial = self.text(&t.initial, scope)?;
|
||||||
|
let submit = self.command(&t.submit, scope)?;
|
||||||
|
Node::TextInput(TextInputNode { common, placeholder, initial, submit, ..t.clone() })
|
||||||
|
}
|
||||||
|
Node::Select(s) => {
|
||||||
|
let common = self.common(&s.common, scope, root)?;
|
||||||
|
let options = match &s.options {
|
||||||
|
OptionList::Literal(_) => s.options.clone(),
|
||||||
|
OptionList::Bound(bound) => OptionList::Bound(BoundOptions {
|
||||||
|
collection: self.collection(&bound.collection, scope)?,
|
||||||
|
value_member: bound.value_member.clone(),
|
||||||
|
label_member: bound.label_member.clone(),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
let value = self.bind(&s.value);
|
||||||
|
let on_change = self.command(&s.on_change, scope)?;
|
||||||
|
Node::Select(SelectNode { common, options, value, on_change })
|
||||||
|
}
|
||||||
|
Node::Repeat(r) => {
|
||||||
|
let common = self.common(&r.common, scope, root)?;
|
||||||
|
let collection = self.collection(&r.collection, scope)?;
|
||||||
|
let template = std::boxed::Box::new(self.node(&r.template, scope, depth + 1, false)?);
|
||||||
|
Node::Repeat(RepeatNode { common, collection, key_member: r.key_member.clone(), template })
|
||||||
|
}
|
||||||
|
Node::Overlay(o) => {
|
||||||
|
let common = self.common(&o.common, scope, root)?;
|
||||||
|
let anchor = match &o.anchor {
|
||||||
|
Anchor::Viewport => Anchor::Viewport,
|
||||||
|
Anchor::Node(anchor) => Anchor::Node(AnchorNode { node: self.id(&anchor.node, scope) }),
|
||||||
|
};
|
||||||
|
let dismiss = self.command(&o.dismiss, scope)?;
|
||||||
|
let children = self.children(&o.children, scope, depth + 1)?;
|
||||||
|
Node::Overlay(OverlayNode { common, anchor, modal: o.modal, dismiss, children })
|
||||||
|
}
|
||||||
|
Node::Plot(p) => {
|
||||||
|
let common = self.common(&p.common, scope, root)?;
|
||||||
|
Node::Plot(PlotNode { common, series: self.bind(&p.series), ..p.clone() })
|
||||||
|
}
|
||||||
|
Node::Embed(e) => {
|
||||||
|
let common = self.common(&e.common, scope, root)?;
|
||||||
|
Node::Embed(EmbedNode { common, ..e.clone() })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- compositions -------------------------------------------------------------------
|
||||||
|
|
||||||
|
fn load(&mut self, reference: &CompositionRef) -> Result<CompositionDocument, (Code, String)> {
|
||||||
|
let name = format!("{}.{}.v{}", reference.publisher, reference.name.as_str(), reference.version.get());
|
||||||
|
if reference.publisher == thing_std::PUBLISHER {
|
||||||
|
return thing_std::lookup(reference.name.as_str(), reference.version)
|
||||||
|
.ok_or((Code::UnresolvedUse, format!("no compiled-in composition {name}")));
|
||||||
|
}
|
||||||
|
let address = Address {
|
||||||
|
provider: ProviderId::new(reference.publisher.clone()),
|
||||||
|
schema: SchemaId::new(CompositionDocument::SCHEMA_NAME),
|
||||||
|
key: RecordKey::new(reference.record_key()),
|
||||||
|
};
|
||||||
|
self.reads.insert(address.clone());
|
||||||
|
match self.port.read(&address) {
|
||||||
|
Lookup::Present(entry) => match entry.record {
|
||||||
|
Record::Composition(composition) => Ok(composition),
|
||||||
|
_ => Err((Code::CompositionInvalid, format!("the record at {name} is not a composition"))),
|
||||||
|
},
|
||||||
|
Lookup::Absent => Err((Code::UnresolvedUse, format!("no composition published at {name}"))),
|
||||||
|
Lookup::Refused(refusal) => Err((Code::DecodeRefused, format!("{name}: {}", refusal.detail))),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first thing wrong with the composition against its Use, if anything.
|
||||||
|
fn misfit(reference: &CompositionRef, composition: &CompositionDocument, args: &[Arg]) -> Option<String> {
|
||||||
|
if composition.publisher != reference.publisher
|
||||||
|
|| composition.name != reference.name
|
||||||
|
|| composition.version != reference.version
|
||||||
|
{
|
||||||
|
return Some("the composition record's publisher, name or version differs from the Use's reference".into());
|
||||||
|
}
|
||||||
|
let mut declared: HashMap<&str, &ParamKind> = HashMap::new();
|
||||||
|
for param in &composition.params {
|
||||||
|
if declared.insert(¶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(""),
|
||||||
|
}
|
||||||
|
}
|
||||||
165
crates/thing-core/src/resolve/intake.rs
Normal file
165
crates/thing-core/src/resolve/intake.rs
Normal file
|
|
@ -0,0 +1,165 @@
|
||||||
|
//! The Resolver: per surface, the highest version offered, the last good tree and the composition
|
||||||
|
//! interests that tree's resolution read. It is handed the changes the frame owner drained and
|
||||||
|
//! never drains itself. Every re-resolve reads the port again; no composition is cached here. The
|
||||||
|
//! interests are held through the shared `Ledger`, so the Binder and the Resolver count one
|
||||||
|
//! subscription per address.
|
||||||
|
|
||||||
|
use std::collections::{HashMap, HashSet};
|
||||||
|
|
||||||
|
use thing_contract::{DatabaseEntry, SurfaceDocument, Version};
|
||||||
|
|
||||||
|
use super::{Limits, ResolvedTree, resolve};
|
||||||
|
use crate::diagnostic::{Code, Diagnostic};
|
||||||
|
use crate::port::{Address, Change, Interest, Ledger, Record, StatePort};
|
||||||
|
|
||||||
|
/// What the Resolver holds of one surface.
|
||||||
|
struct Held {
|
||||||
|
/// The highest version offered, accepted or refused: the only one resolved again.
|
||||||
|
document: SurfaceDocument,
|
||||||
|
/// The last tree a resolve produced for a version above every earlier one.
|
||||||
|
tree: Option<ResolvedTree>,
|
||||||
|
/// The interests of the last resolve, which was of `document`.
|
||||||
|
interests: HashSet<Interest>,
|
||||||
|
/// Versions already reported stale.
|
||||||
|
reported: HashSet<Version>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What one `apply` did: its diagnostics, and each surface key whose displayed tree it replaced
|
||||||
|
/// (`true`) or dropped (`false`), sorted by key. A re-resolve that failed keeps its tree and is
|
||||||
|
/// not listed, so the frame owner never infers a change by comparing trees.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq)]
|
||||||
|
pub struct Intake {
|
||||||
|
pub diagnostics: Vec<Diagnostic>,
|
||||||
|
pub changed: Vec<(String, bool)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Resolver {
|
||||||
|
limits: Limits,
|
||||||
|
surfaces: HashMap<String, Held>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_surface(address: &Address) -> bool {
|
||||||
|
address.schema.as_str() == SurfaceDocument::SCHEMA_NAME
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Resolver {
|
||||||
|
pub fn new(limits: Limits) -> Self {
|
||||||
|
Self { limits, surfaces: HashMap::new() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The tree displayed for a surface key: the last good one.
|
||||||
|
pub fn tree(&self, surface_key: &str) -> Option<&ResolvedTree> {
|
||||||
|
self.surfaces.get(surface_key).and_then(|held| held.tree.as_ref())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drop a surface the consumer no longer shows: its interests are released and its entry goes
|
||||||
|
/// with no tombstone (the consumer leaving is not the provider deleting).
|
||||||
|
pub fn forget(&mut self, surface_key: &str, port: &mut dyn StatePort, ledger: &mut Ledger) {
|
||||||
|
if let Some(held) = self.surfaces.remove(surface_key) {
|
||||||
|
ledger.diff(port, &held.interests, &HashSet::new());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One drained change. A surface offer is judged by the version rule; a change at a
|
||||||
|
/// composition a held surface read resolves that surface again from its held document.
|
||||||
|
pub fn apply(&mut self, change: &Change, port: &mut dyn StatePort, ledger: &mut Ledger) -> Intake {
|
||||||
|
let address = match change {
|
||||||
|
Change::Upsert(entry) => &entry.address,
|
||||||
|
Change::Delete(address) => address,
|
||||||
|
Change::Refused(refusal) => &refusal.address,
|
||||||
|
};
|
||||||
|
if is_surface(address) {
|
||||||
|
return match change {
|
||||||
|
Change::Upsert(entry) => match &entry.record {
|
||||||
|
Record::Surface(document) => self.offer(document, port, ledger),
|
||||||
|
_ => Intake::default(),
|
||||||
|
},
|
||||||
|
Change::Delete(address) => {
|
||||||
|
// A tombstone: the highest version stays so an older one is not taken again,
|
||||||
|
// but the tree and the interests go.
|
||||||
|
let mut changed = Vec::new();
|
||||||
|
if let Some(held) = self.surfaces.get_mut(address.key.as_str()) {
|
||||||
|
if held.tree.take().is_some() {
|
||||||
|
changed.push((address.key.as_str().to_string(), false));
|
||||||
|
}
|
||||||
|
let released = std::mem::take(&mut held.interests);
|
||||||
|
ledger.diff(port, &released, &HashSet::new());
|
||||||
|
}
|
||||||
|
Intake { diagnostics: Vec::new(), changed }
|
||||||
|
}
|
||||||
|
Change::Refused(refusal) => Intake {
|
||||||
|
diagnostics: vec![Diagnostic {
|
||||||
|
code: Code::DecodeRefused,
|
||||||
|
surface: address.key.as_str().to_string(),
|
||||||
|
node: None,
|
||||||
|
detail: refusal.detail.clone(),
|
||||||
|
}],
|
||||||
|
changed: Vec::new(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
let mut readers: Vec<String> = self
|
||||||
|
.surfaces
|
||||||
|
.iter()
|
||||||
|
.filter(|(_, held)| held.interests.iter().any(|interest| interest.matches(address)))
|
||||||
|
.map(|(key, _)| key.clone())
|
||||||
|
.collect();
|
||||||
|
readers.sort();
|
||||||
|
let mut intake = Intake::default();
|
||||||
|
for key in readers {
|
||||||
|
let document = self.surfaces[&key].document.clone();
|
||||||
|
let (diagnostics, replaced) = self.resolve_held(&key, document, port, ledger);
|
||||||
|
intake.diagnostics.extend(diagnostics);
|
||||||
|
if replaced {
|
||||||
|
intake.changed.push((key, true));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
intake
|
||||||
|
}
|
||||||
|
|
||||||
|
fn offer(&mut self, document: &SurfaceDocument, port: &mut dyn StatePort, ledger: &mut Ledger) -> Intake {
|
||||||
|
let key = document.record_key();
|
||||||
|
if let Some(held) = self.surfaces.get_mut(&key)
|
||||||
|
&& document.version <= held.document.version
|
||||||
|
{
|
||||||
|
// A subscribe replays the current record: the same document again is not news.
|
||||||
|
let diagnostics = if document.version == held.document.version && *document == held.document {
|
||||||
|
Vec::new()
|
||||||
|
} else if held.reported.insert(document.version) {
|
||||||
|
vec![Diagnostic {
|
||||||
|
code: Code::StaleVersionIgnored,
|
||||||
|
surface: key,
|
||||||
|
node: None,
|
||||||
|
detail: "version at or below the held version, which stays".into(),
|
||||||
|
}]
|
||||||
|
} else {
|
||||||
|
Vec::new()
|
||||||
|
};
|
||||||
|
return Intake { diagnostics, changed: Vec::new() };
|
||||||
|
}
|
||||||
|
let (diagnostics, replaced) = self.resolve_held(&key, document.clone(), port, ledger);
|
||||||
|
Intake { diagnostics, changed: if replaced { vec![(key, true)] } else { Vec::new() } }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve `document` as the highest offered for `key`: a tree replaces the held one, no tree
|
||||||
|
/// keeps it. The interests become the reads either way. The flag is whether a tree replaced
|
||||||
|
/// the held one.
|
||||||
|
fn resolve_held(&mut self, key: &str, document: SurfaceDocument, port: &mut dyn StatePort, ledger: &mut Ledger) -> (Vec<Diagnostic>, bool) {
|
||||||
|
let resolution = resolve(&document, &*port, &self.limits);
|
||||||
|
let interests: HashSet<Interest> = resolution.reads.into_iter().map(Interest::Record).collect();
|
||||||
|
let held = self.surfaces.entry(key.to_string()).or_insert_with(|| Held {
|
||||||
|
document: document.clone(),
|
||||||
|
tree: None,
|
||||||
|
interests: HashSet::new(),
|
||||||
|
reported: HashSet::new(),
|
||||||
|
});
|
||||||
|
ledger.diff(port, &held.interests, &interests);
|
||||||
|
held.interests = interests;
|
||||||
|
held.document = document;
|
||||||
|
let replaced = resolution.tree.is_some();
|
||||||
|
if let Some(tree) = resolution.tree {
|
||||||
|
held.tree = Some(tree);
|
||||||
|
}
|
||||||
|
(resolution.diagnostics, replaced)
|
||||||
|
}
|
||||||
|
}
|
||||||
111
crates/thing-core/src/resolve/mod.rs
Normal file
111
crates/thing-core/src/resolve/mod.rs
Normal file
|
|
@ -0,0 +1,111 @@
|
||||||
|
//! Resolve: the pure expansion of a surface document into a tree with no composition left in it.
|
||||||
|
//! This is the only code that reads Thing Script structure (Use, Param, CommandRef, node ids).
|
||||||
|
//! It reads compositions through `StatePort::read` and `thing.std` from a compiled-in table,
|
||||||
|
//! holds no state, subscribes to nothing and never drains; `Resolver` is the stateful half.
|
||||||
|
|
||||||
|
mod expand;
|
||||||
|
mod intake;
|
||||||
|
pub mod std;
|
||||||
|
mod validate;
|
||||||
|
|
||||||
|
use thing_contract::SurfaceDocument;
|
||||||
|
|
||||||
|
pub use intake::{Intake, Resolver};
|
||||||
|
|
||||||
|
use crate::diagnostic::{Code, Diagnostic};
|
||||||
|
use crate::port::{Address, StatePort};
|
||||||
|
|
||||||
|
/// Stack left below which recursion moves to a fresh segment, and the segment's size: the values
|
||||||
|
/// cultcache-rs uses for decode. Every recursion over a tree runs through `grow`, so a tree as deep
|
||||||
|
/// as `STACK_BOUND` resolves on a default thread.
|
||||||
|
const RED_ZONE: usize = 512 * 1024;
|
||||||
|
const SEGMENT: usize = 2 * 1024 * 1024;
|
||||||
|
|
||||||
|
/// Runs one recursive step with room for the next, growing the stack when it is nearly spent.
|
||||||
|
pub(crate) fn grow<R>(step: impl FnOnce() -> R) -> R {
|
||||||
|
stacker::maybe_grow(RED_ZONE, SEGMENT, step)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The bounds of one expansion.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct Limits {
|
||||||
|
/// Compositions nested in one another; a Use deeper than this is a placeholder.
|
||||||
|
pub max_use_depth: usize,
|
||||||
|
/// The contract's decode bound; a deeper expanded tree is refused.
|
||||||
|
pub max_tree_depth: usize,
|
||||||
|
/// Nodes in the expanded tree; more is refused.
|
||||||
|
pub max_nodes: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Limits {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self { max_use_depth: 32, max_tree_depth: 256, max_nodes: 65_536 }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A surface document expanded: no Param of any kind remains, every command is declared, every
|
||||||
|
/// state reference names its provider, node ids are unique, and a Use remains only as a
|
||||||
|
/// placeholder leaf (its arguments emptied) beside a diagnostic. Only `resolve` builds one.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct ResolvedTree {
|
||||||
|
document: SurfaceDocument,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ResolvedTree {
|
||||||
|
pub fn document(&self) -> &SurfaceDocument {
|
||||||
|
&self.document
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What one expansion found. `tree` is `None` when a fault refuses the whole document.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct Resolution {
|
||||||
|
pub tree: Option<ResolvedTree>,
|
||||||
|
/// Expansion faults in expansion pre-order, then the finished tree's faults (duplicate ids, depth)
|
||||||
|
/// in tree pre-order.
|
||||||
|
pub diagnostics: Vec<Diagnostic>,
|
||||||
|
/// Every non-std composition address consulted, whether present, absent or refused, once each, ordered
|
||||||
|
/// by provider, schema and key.
|
||||||
|
pub reads: Vec<Address>,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resolve(document: &SurfaceDocument, port: &dyn StatePort, limits: &Limits) -> Resolution {
|
||||||
|
let mut expander = expand::Expander::new(document, port, limits);
|
||||||
|
let root = match expander.root(&document.root) {
|
||||||
|
Ok(root) => Some(root),
|
||||||
|
Err(expand::Fault::Limit(detail)) => {
|
||||||
|
expander.diag(Code::ExpansionLimit, None, detail);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
Err(expand::Fault::Stack(detail)) => {
|
||||||
|
expander.diag(Code::TooDeepToResolve, None, detail);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
Err(expand::Fault::Invalid(detail)) => {
|
||||||
|
expander.diag(Code::CompositionInvalid, None, detail);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let mut diagnostics = ::std::mem::take(&mut expander.diagnostics);
|
||||||
|
let mut reads: Vec<Address> = ::std::mem::take(&mut expander.reads).into_iter().collect();
|
||||||
|
reads.sort_by(|a, b| {
|
||||||
|
let key = |address: &Address| (address.provider.as_str().to_string(), address.schema.as_str().to_string(), address.key.as_str().to_string());
|
||||||
|
key(a).cmp(&key(b))
|
||||||
|
});
|
||||||
|
let tree = root.and_then(|root| {
|
||||||
|
diagnostics.extend(validate::check(&root, &document.commands, limits, &document.record_key()));
|
||||||
|
let refused = diagnostics.iter().any(|diagnostic| diagnostic.code.refuses_document());
|
||||||
|
// Field by field: `..document.clone()` would clone the whole input tree to discard it.
|
||||||
|
(!refused).then(|| ResolvedTree {
|
||||||
|
document: SurfaceDocument {
|
||||||
|
provider_id: document.provider_id.clone(),
|
||||||
|
label: document.label.clone(),
|
||||||
|
version: document.version,
|
||||||
|
title: document.title.clone(),
|
||||||
|
root,
|
||||||
|
commands: document.commands.clone(),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
});
|
||||||
|
Resolution { tree, diagnostics, reads }
|
||||||
|
}
|
||||||
95
crates/thing-core/src/resolve/std.rs
Normal file
95
crates/thing-core/src/resolve/std.rs
Normal file
|
|
@ -0,0 +1,95 @@
|
||||||
|
//! `thing.std`: the compositions compiled into core. The port is never asked for this
|
||||||
|
//! publisher, so no provider can shadow one.
|
||||||
|
|
||||||
|
use thing_contract::*;
|
||||||
|
|
||||||
|
/// The publisher whose compositions are compiled in.
|
||||||
|
pub const PUBLISHER: &str = "thing.std";
|
||||||
|
|
||||||
|
/// Every compiled-in composition.
|
||||||
|
pub fn all() -> Vec<CompositionDocument> {
|
||||||
|
vec![stat(), card()]
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn lookup(name: &str, version: Version) -> Option<CompositionDocument> {
|
||||||
|
all().into_iter().find(|composition| composition.name.as_str() == name && composition.version == version)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn segment(name: &str) -> Segment {
|
||||||
|
Segment::new(name).expect("a std name is a segment")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn common(id: &str) -> NodeCommon {
|
||||||
|
NodeCommon { id: NodeId::new(id), visible: BoolSource::Literal(BoolLiteral { value: true }), a11y_label: None }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn text(id: &str, content: TextSource, style_token: &str) -> Node {
|
||||||
|
Node::Text(TextNode {
|
||||||
|
common: common(id),
|
||||||
|
content,
|
||||||
|
style_token: style_token.into(),
|
||||||
|
wrap: true,
|
||||||
|
max_lines: None,
|
||||||
|
selectable: false,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn param(name: &str) -> ParamName {
|
||||||
|
ParamName { name: name.into() }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn column(id: &str, children: Vec<Node>) -> Node {
|
||||||
|
let zero = || Dimension::Px(Scalar { value: 0.0 });
|
||||||
|
let auto = || Dimension::Auto;
|
||||||
|
let size = |width, height| Size2 { width, height };
|
||||||
|
let edges = |all: Dimension| Edges { top: all.clone(), right: all.clone(), bottom: all.clone(), left: all };
|
||||||
|
let style = BoxStyle {
|
||||||
|
display: Display::Flex,
|
||||||
|
direction: Direction::Column,
|
||||||
|
wrap: Wrap::NoWrap,
|
||||||
|
gap: size(zero(), Dimension::Px(Scalar { value: 4.0 })),
|
||||||
|
padding: edges(zero()),
|
||||||
|
margin: edges(zero()),
|
||||||
|
size: size(auto(), Dimension::Content),
|
||||||
|
min_size: size(zero(), zero()),
|
||||||
|
max_size: size(auto(), auto()),
|
||||||
|
position: Position::Relative,
|
||||||
|
inset: edges(auto()),
|
||||||
|
overflow: Overflow::Visible,
|
||||||
|
align_items: ItemAlign::Stretch,
|
||||||
|
align_self: ItemAlign::Auto,
|
||||||
|
align_content: ContentAlign::Start,
|
||||||
|
justify_content: ContentAlign::Start,
|
||||||
|
grow: 0.0,
|
||||||
|
shrink: 1.0,
|
||||||
|
basis: Dimension::Auto,
|
||||||
|
grid_columns: vec![],
|
||||||
|
grid_rows: vec![],
|
||||||
|
};
|
||||||
|
let paint = Paint { background: None, border: None, radius: 0.0 };
|
||||||
|
Node::Box(BoxNode { common: common(id), style, paint, role: Role::Group, children })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn composition(name: &str, params: &[(&str, ParamKind)], body: Node) -> CompositionDocument {
|
||||||
|
CompositionDocument {
|
||||||
|
publisher: PUBLISHER.into(),
|
||||||
|
name: segment(name),
|
||||||
|
version: Version::new(1).expect("version 1"),
|
||||||
|
params: params.iter().map(|(name, kind)| ParamDecl { name: (*name).into(), kind: kind.clone() }).collect(),
|
||||||
|
body,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A label over a bound value.
|
||||||
|
fn stat() -> CompositionDocument {
|
||||||
|
let label = text("stat-label", TextSource::Param(param("label")), "caption");
|
||||||
|
let value = text("stat-value", TextSource::Param(param("value")), "title");
|
||||||
|
composition("stat", &[("label", ParamKind::Text), ("value", ParamKind::Bind)], column("stat-root", vec![label, value]))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A title over the nodes passed for `body`.
|
||||||
|
fn card() -> CompositionDocument {
|
||||||
|
let title = text("card-title", TextSource::Param(param("title")), "title");
|
||||||
|
let slot = Node::Slot(SlotNode { param: param("body") });
|
||||||
|
composition("card", &[("title", ParamKind::Text), ("body", ParamKind::Slot)], column("card-root", vec![title, slot]))
|
||||||
|
}
|
||||||
119
crates/thing-core/src/resolve/validate.rs
Normal file
119
crates/thing-core/src/resolve/validate.rs
Normal file
|
|
@ -0,0 +1,119 @@
|
||||||
|
//! The one pass over the finished tree: ids unique, and the tree within its depth limit (a slot's
|
||||||
|
//! nodes are placed deeper than expand saw them). Commands, Params and Slots are judged where they
|
||||||
|
//! land and the node count is expand's alone (it must stop before it builds a tree it would refuse).
|
||||||
|
|
||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
|
use thing_contract::{CommandDecl, Node, NodeId};
|
||||||
|
|
||||||
|
use super::Limits;
|
||||||
|
use crate::diagnostic::{Code, Diagnostic};
|
||||||
|
|
||||||
|
/// The child nodes of a node, in order.
|
||||||
|
fn children(node: &Node) -> &[Node] {
|
||||||
|
match node {
|
||||||
|
Node::Box(b) => &b.children,
|
||||||
|
Node::Button(b) => &b.content,
|
||||||
|
Node::Overlay(o) => &o.children,
|
||||||
|
Node::Repeat(r) => std::slice::from_ref(&*r.template),
|
||||||
|
_ => &[],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn id(node: &Node) -> Option<&NodeId> {
|
||||||
|
match node {
|
||||||
|
Node::Box(n) => Some(&n.common.id),
|
||||||
|
Node::Text(n) => Some(&n.common.id),
|
||||||
|
Node::Image(n) => Some(&n.common.id),
|
||||||
|
Node::Button(n) => Some(&n.common.id),
|
||||||
|
Node::Toggle(n) => Some(&n.common.id),
|
||||||
|
Node::Slider(n) => Some(&n.common.id),
|
||||||
|
Node::TextInput(n) => Some(&n.common.id),
|
||||||
|
Node::Select(n) => Some(&n.common.id),
|
||||||
|
Node::Repeat(n) => Some(&n.common.id),
|
||||||
|
Node::Overlay(n) => Some(&n.common.id),
|
||||||
|
Node::Plot(n) => Some(&n.common.id),
|
||||||
|
Node::Embed(n) => Some(&n.common.id),
|
||||||
|
Node::Use(n) => Some(&n.common.id),
|
||||||
|
Node::Slot(_) => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Nodes in the subtree, the node itself included.
|
||||||
|
pub(super) fn size(node: &Node) -> usize {
|
||||||
|
super::grow(|| 1 + children(node).iter().map(size).sum::<usize>())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Faults of the finished tree, in pre-order: duplicate ids, then depth, then each command capture that is not an input node. A tree deeper than the limit is not walked further.
|
||||||
|
pub(super) fn check(root: &Node, commands: &[CommandDecl], limits: &Limits, surface: &str) -> Vec<Diagnostic> {
|
||||||
|
let mut found = Vec::new();
|
||||||
|
let fault = |code, node: Option<&NodeId>, detail: String| Diagnostic {
|
||||||
|
code,
|
||||||
|
surface: surface.to_string(),
|
||||||
|
node: node.cloned(),
|
||||||
|
detail,
|
||||||
|
};
|
||||||
|
let mut seen: HashSet<&NodeId> = HashSet::new();
|
||||||
|
let mut inputs: HashSet<&NodeId> = HashSet::new();
|
||||||
|
let mut too_deep = false;
|
||||||
|
let mut stack = vec![(root, 1usize)];
|
||||||
|
while let Some((node, depth)) = stack.pop() {
|
||||||
|
if depth > limits.max_tree_depth {
|
||||||
|
too_deep = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(id) = id(node) {
|
||||||
|
if matches!(node, Node::Toggle(_) | Node::Slider(_) | Node::Select(_) | Node::TextInput(_)) {
|
||||||
|
inputs.insert(id);
|
||||||
|
}
|
||||||
|
if !seen.insert(id) {
|
||||||
|
found.push(fault(Code::DuplicateNodeId, Some(id), format!("node id '{}' occurs twice", id.as_str())));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
stack.extend(children(node).iter().rev().map(|child| (child, depth + 1)));
|
||||||
|
}
|
||||||
|
if too_deep {
|
||||||
|
found.push(fault(Code::ExpansionLimit, None, format!("the tree is deeper than {} levels", limits.max_tree_depth)));
|
||||||
|
}
|
||||||
|
for capture in commands.iter().flat_map(|decl| &decl.captures) {
|
||||||
|
if !inputs.contains(capture) {
|
||||||
|
found.push(fault(Code::CaptureUndeclared, Some(capture), format!("capture '{}' is not an input node of the surface", capture.as_str())));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
found
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use thing_testkit::build::{boxed, text};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
/// Runs `work` with about `left` bytes of stack remaining: the stack is burned first, so a recursion
|
||||||
|
/// that does not grow its own runs out inside it.
|
||||||
|
#[inline(never)]
|
||||||
|
fn with_stack_left(left: usize, work: &mut dyn FnMut()) {
|
||||||
|
if stacker::remaining_stack().expect("the thread's stack limit is known") > left {
|
||||||
|
let burn = [0u8; 4096];
|
||||||
|
std::hint::black_box(&burn);
|
||||||
|
with_stack_left(left, work);
|
||||||
|
std::hint::black_box(&burn);
|
||||||
|
} else {
|
||||||
|
work();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn size_of_a_deep_subtree_grows_its_own_stack() {
|
||||||
|
// expand counts a slot argument with `size` after the argument was expanded, from wherever the
|
||||||
|
// stack stands; a 1,000-level argument must not run it out.
|
||||||
|
let mut deep = text("bottom", "x");
|
||||||
|
for level in 1..1000 {
|
||||||
|
deep = boxed(&format!("level-{level}"), vec![deep]);
|
||||||
|
}
|
||||||
|
let mut counted = 0;
|
||||||
|
with_stack_left(100 * 1024, &mut || counted = size(&deep));
|
||||||
|
assert_eq!(counted, 1000);
|
||||||
|
// Dropping a tree this deep needs the room the test thread has outside `with_stack_left`.
|
||||||
|
}
|
||||||
|
}
|
||||||
317
crates/thing-core/src/text/cells.rs
Normal file
317
crates/thing-core/src/text/cells.rs
Normal file
|
|
@ -0,0 +1,317 @@
|
||||||
|
//! The Cells text engine: `CellText` is the one constructor of terminal text and `CellMeasure` the
|
||||||
|
//! one `Measure` for Cells. Every width and every break a cell backend advances by is decided
|
||||||
|
//! here, per extended grapheme cluster, and no backend computes either.
|
||||||
|
//!
|
||||||
|
//! Order is sanitize, then segment and measure: the text is cleaned (controls become U+FFFD,
|
||||||
|
//! clusters without width are dropped) until segmenting it again changes nothing, so every width
|
||||||
|
//! recorded is the width of exactly the text a terminal receives.
|
||||||
|
//!
|
||||||
|
//! Breaking is CSS `white-space: pre-wrap` with `overflow-wrap: break-word`: mandatory breaks
|
||||||
|
//! always break, soft breaks are UAX #14 Allowed positions on a cluster boundary, trailing spaces
|
||||||
|
//! at a soft break hang (are not emitted), and an unbreakable segment wider than the line breaks
|
||||||
|
//! between clusters. A line takes at least one cluster, so at width 0 every cluster sits on its
|
||||||
|
//! own line. Text is laid out in logical order; bidi reordering is Pixels-only.
|
||||||
|
|
||||||
|
use unicode_linebreak::{BreakOpportunity, linebreaks};
|
||||||
|
use unicode_segmentation::UnicodeSegmentation;
|
||||||
|
use unicode_width::UnicodeWidthStr;
|
||||||
|
|
||||||
|
use crate::bind::Bound;
|
||||||
|
use crate::layout::{Avail, CELL_PX, CellStyle, Constraint, Leaf, Measure, Run, TextLayout, TextLine, TextRequest};
|
||||||
|
|
||||||
|
/// The tab stop, in columns (CSS `tab-size: 8`).
|
||||||
|
const TAB: u32 = 8;
|
||||||
|
|
||||||
|
/// Terminal text: a string with one width per extended grapheme cluster, free of control
|
||||||
|
/// characters and of zero-width clusters, whose clusters re-segment to themselves. A document
|
||||||
|
/// never writes an escape code into a terminal because no other constructor exists.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||||
|
pub struct CellText {
|
||||||
|
text: String,
|
||||||
|
/// The end byte offset and the width in cells of each cluster, in order.
|
||||||
|
clusters: Vec<(u32, u8)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CellText {
|
||||||
|
/// One line of terminal text. Tabs stop at multiples of 8 columns from the start of `text`;
|
||||||
|
/// every control character, line terminators included, becomes U+FFFD (width 1); a cluster
|
||||||
|
/// without width is dropped.
|
||||||
|
pub fn new(text: &str) -> Self {
|
||||||
|
let (clean, open) = clean(text);
|
||||||
|
emit(&atoms(&clean, &open))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn as_str(&self) -> &str {
|
||||||
|
&self.text
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Each cluster with its width in cells.
|
||||||
|
pub fn clusters(&self) -> impl Iterator<Item = (&str, u8)> {
|
||||||
|
let mut start = 0;
|
||||||
|
self.clusters.iter().map(move |&(end, width)| {
|
||||||
|
let cluster = &self.text[start as usize..end as usize];
|
||||||
|
start = end as usize;
|
||||||
|
(cluster, width)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The width of the line in cells: the sum of its cluster widths.
|
||||||
|
pub fn width(&self) -> u32 {
|
||||||
|
self.clusters.iter().map(|&(_, w)| u32::from(w)).sum()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One kept cluster of a paragraph and whether a soft break may precede it. A tab is an atom of
|
||||||
|
/// its own: its width is decided where it falls in a line.
|
||||||
|
struct Atom<'a> {
|
||||||
|
text: &'a str,
|
||||||
|
width: u8,
|
||||||
|
tab: bool,
|
||||||
|
space: bool,
|
||||||
|
open: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Atom<'_> {
|
||||||
|
/// The columns this atom takes when it starts at `column` of its line.
|
||||||
|
fn cols(&self, column: u32) -> u32 {
|
||||||
|
if self.tab { TAB - column % TAB } else { u32::from(self.width) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_terminator(c: char) -> bool {
|
||||||
|
matches!(c, '\n' | '\r' | '\u{b}' | '\u{c}' | '\u{85}' | '\u{2028}' | '\u{2029}')
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sanitize, to a fixpoint: every control (a tab excepted) becomes U+FFFD and every cluster
|
||||||
|
/// without width is dropped, and since either can change how the rest segments, the result is
|
||||||
|
/// segmented again until nothing more changes. Returns the text and, by byte offset, where a soft
|
||||||
|
/// break may fall; the opportunity at a dropped cluster rides on the next kept one.
|
||||||
|
fn clean(paragraph: &str) -> (String, Vec<bool>) {
|
||||||
|
let mut open = vec![false; paragraph.len() + 1];
|
||||||
|
for (at, kind) in linebreaks(paragraph) {
|
||||||
|
if kind == BreakOpportunity::Allowed {
|
||||||
|
open[at] = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut text = paragraph.to_owned();
|
||||||
|
loop {
|
||||||
|
let mut out = String::with_capacity(text.len());
|
||||||
|
let mut marks = Vec::new();
|
||||||
|
let (mut pending, mut changed) = (false, false);
|
||||||
|
for (start, cluster) in text.grapheme_indices(true) {
|
||||||
|
let here = open[start] || pending;
|
||||||
|
pending = false;
|
||||||
|
let first = cluster.chars().next().expect("a cluster has a scalar");
|
||||||
|
let kept = if cluster == "\t" {
|
||||||
|
cluster
|
||||||
|
} else if first.is_control() || is_terminator(first) {
|
||||||
|
changed = true;
|
||||||
|
"\u{fffd}"
|
||||||
|
} else if cluster.width() == 0 {
|
||||||
|
(pending, changed) = (here, true);
|
||||||
|
continue;
|
||||||
|
} else {
|
||||||
|
cluster
|
||||||
|
};
|
||||||
|
if here {
|
||||||
|
marks.push(out.len());
|
||||||
|
}
|
||||||
|
out.push_str(kept);
|
||||||
|
}
|
||||||
|
if !changed {
|
||||||
|
return (text, open);
|
||||||
|
}
|
||||||
|
open = vec![false; out.len() + 1];
|
||||||
|
for mark in marks {
|
||||||
|
open[mark] = true;
|
||||||
|
}
|
||||||
|
text = out;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The clusters of cleaned text.
|
||||||
|
fn atoms<'a>(text: &'a str, open: &[bool]) -> Vec<Atom<'a>> {
|
||||||
|
let mut out: Vec<Atom> = text
|
||||||
|
.grapheme_indices(true)
|
||||||
|
.map(|(start, cluster)| {
|
||||||
|
let tab = cluster == "\t";
|
||||||
|
Atom { text: cluster, width: if tab { 0 } else { cluster.width().min(255) as u8 }, tab, space: tab || cluster == " ", open: open[start] }
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
if let Some(first) = out.first_mut() {
|
||||||
|
first.open = false;
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One line as terminal text: tabs become spaces to the next stop from the line's start, and the
|
||||||
|
/// result is cleaned and segmented once more, so its recorded widths are those of the emitted text.
|
||||||
|
fn emit(line: &[Atom]) -> CellText {
|
||||||
|
let mut text = String::new();
|
||||||
|
let mut column = 0;
|
||||||
|
for atom in line {
|
||||||
|
let cols = atom.cols(column);
|
||||||
|
if atom.tab {
|
||||||
|
text.extend(std::iter::repeat_n(' ', cols as usize));
|
||||||
|
} else {
|
||||||
|
text.push_str(atom.text);
|
||||||
|
}
|
||||||
|
column += cols;
|
||||||
|
}
|
||||||
|
let (text, _) = clean(&text);
|
||||||
|
let mut out = CellText::default();
|
||||||
|
for cluster in text.graphemes(true) {
|
||||||
|
out.text.push_str(cluster);
|
||||||
|
out.clusters.push((out.text.len() as u32, cluster.width().min(255) as u8));
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The paragraphs of `text`: the pieces between mandatory breaks, terminators removed. A final
|
||||||
|
/// terminator ends the last line and starts no empty one.
|
||||||
|
fn paragraphs(text: &str) -> Vec<&str> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut from = 0;
|
||||||
|
for (at, kind) in linebreaks(text) {
|
||||||
|
if kind == BreakOpportunity::Mandatory && at < text.len() {
|
||||||
|
out.push(strip_terminator(&text[from..at]));
|
||||||
|
from = at;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push(strip_terminator(&text[from..]));
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn strip_terminator(piece: &str) -> &str {
|
||||||
|
match piece.graphemes(true).next_back() {
|
||||||
|
Some(last) if last.chars().any(is_terminator) => &piece[..piece.len() - last.len()],
|
||||||
|
_ => piece,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The lines of `text` at `cols` columns. `wrap` off breaks at mandatory breaks only.
|
||||||
|
fn break_lines(text: &str, wrap: bool, max_lines: Option<u32>, cols: u32) -> Vec<CellText> {
|
||||||
|
let cap = max_lines.map_or(usize::MAX, |n| n as usize);
|
||||||
|
let mut lines = Vec::new();
|
||||||
|
for paragraph in paragraphs(text) {
|
||||||
|
let (clean, open) = clean(paragraph);
|
||||||
|
let atoms = atoms(&clean, &open);
|
||||||
|
let mut start = 0;
|
||||||
|
loop {
|
||||||
|
if lines.len() >= cap {
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
let end = if wrap { fit(&atoms, start, cols) } else { atoms.len() };
|
||||||
|
let mut line = &atoms[start..end];
|
||||||
|
if end < atoms.len() && line.iter().any(|a| !a.space) {
|
||||||
|
// A soft break: the spaces before it hang.
|
||||||
|
while let Some((last, rest)) = line.split_last() {
|
||||||
|
if !last.space {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
line = rest;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lines.push(emit(line));
|
||||||
|
if end >= atoms.len() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
start = end;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lines
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the line that starts at `start` ends: the last soft break that fits, else the last
|
||||||
|
/// cluster that fits, else (a cluster wider than the room) just that cluster. Spaces hang: they
|
||||||
|
/// never overflow a line.
|
||||||
|
fn fit(atoms: &[Atom], start: usize, cols: u32) -> usize {
|
||||||
|
let (mut width, mut shown) = (0u32, 0u32);
|
||||||
|
let mut candidate = None;
|
||||||
|
for (i, atom) in atoms.iter().enumerate().skip(start) {
|
||||||
|
if atom.open && i > start {
|
||||||
|
candidate = Some(i);
|
||||||
|
}
|
||||||
|
width += atom.cols(width);
|
||||||
|
if !atom.space {
|
||||||
|
shown = width;
|
||||||
|
if shown > cols && i > start {
|
||||||
|
return candidate.unwrap_or(i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
atoms.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The widest unbreakable segment, trailing spaces excluded.
|
||||||
|
fn longest_segment(text: &str) -> u32 {
|
||||||
|
let mut widest = 0;
|
||||||
|
for paragraph in paragraphs(text) {
|
||||||
|
let (clean, open) = clean(paragraph);
|
||||||
|
let (mut column, mut from, mut shown) = (0, 0, 0);
|
||||||
|
for atom in atoms(&clean, &open) {
|
||||||
|
if atom.open {
|
||||||
|
widest = widest.max(shown - from);
|
||||||
|
(from, shown) = (column, column);
|
||||||
|
}
|
||||||
|
column += atom.cols(column);
|
||||||
|
if !atom.space {
|
||||||
|
shown = column;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
widest = widest.max(shown - from);
|
||||||
|
}
|
||||||
|
widest
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lines_for(text: &str, wrap: bool, max_lines: Option<u32>, room: Avail) -> Vec<CellText> {
|
||||||
|
let cols = match room {
|
||||||
|
// `as` saturates: negative and NaN are 0, huge is u32::MAX.
|
||||||
|
Avail::Definite(w) if wrap => w.floor() as u32,
|
||||||
|
_ => u32::MAX,
|
||||||
|
};
|
||||||
|
break_lines(text, wrap, max_lines, cols)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The shipped Cells engine: text by cluster width and UAX #14, controls at fixed cell sizes.
|
||||||
|
#[derive(Clone, Copy, Debug, Default)]
|
||||||
|
pub struct CellMeasure;
|
||||||
|
|
||||||
|
impl Measure for CellMeasure {
|
||||||
|
fn measure(&mut self, leaf: &Leaf, c: Constraint) -> (f32, f32) {
|
||||||
|
match leaf {
|
||||||
|
Leaf::Text { content, wrap, max_lines, .. } => {
|
||||||
|
let text = match content {
|
||||||
|
Bound::Text(text) => text.as_str(),
|
||||||
|
_ => "",
|
||||||
|
};
|
||||||
|
let room = c.known[0].map(Avail::Definite).unwrap_or(c.available[0]);
|
||||||
|
if *wrap && room == Avail::MinContent {
|
||||||
|
let rows = lines_for(text, true, *max_lines, Avail::MaxContent).len();
|
||||||
|
return (longest_segment(text) as f32, rows as f32);
|
||||||
|
}
|
||||||
|
let lines = lines_for(text, *wrap, *max_lines, room);
|
||||||
|
(lines.iter().map(CellText::width).max().unwrap_or(0) as f32, lines.len() as f32)
|
||||||
|
}
|
||||||
|
Leaf::TextInput { multiline, .. } => (25.0, if *multiline { 3.0 } else { 1.0 }),
|
||||||
|
Leaf::Toggle { .. } => (5.0, 1.0),
|
||||||
|
Leaf::Slider { .. } => (20.0, 1.0),
|
||||||
|
Leaf::Select { .. } => (20.0, 1.0),
|
||||||
|
Leaf::Image { asset, .. } => match asset {
|
||||||
|
Bound::Asset(entry) => ((entry.width.get() as f32 / CELL_PX.0).ceil(), (entry.height.get() as f32 / CELL_PX.1).ceil()),
|
||||||
|
_ => (0.0, 0.0),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn text(&mut self, request: &TextRequest, width: f32) -> TextLayout {
|
||||||
|
let lines = lines_for(request.text, request.wrap, request.max_lines, Avail::Definite(width));
|
||||||
|
TextLayout {
|
||||||
|
lines: lines
|
||||||
|
.into_iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(row, text)| TextLine { y: row as f32, height: 1.0, run: Run::Cells { text, style: CellStyle::default() } })
|
||||||
|
.collect(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
6
crates/thing-core/src/text/mod.rs
Normal file
6
crates/thing-core/src/text/mod.rs
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
//! Terminal text: what a string is made of in a cell grid. The one owner of every Cells width and
|
||||||
|
//! line break (Pixels text is the shaper's, behind the same `Measure` seam).
|
||||||
|
|
||||||
|
mod cells;
|
||||||
|
|
||||||
|
pub use cells::{CellMeasure, CellText};
|
||||||
86
crates/thing-core/src/theme.rs
Normal file
86
crates/thing-core/src/theme.rs
Normal file
|
|
@ -0,0 +1,86 @@
|
||||||
|
//! The theme a frame is drawn with: named colours and named text styles, resolved to literals
|
||||||
|
//! in render so a token never reaches a backend. Where a host's theme comes from is
|
||||||
|
//! `thing2:follow_up:theme-record-contract`; render takes a `&Theme`.
|
||||||
|
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use thing_contract::{ColorRef, Rgba};
|
||||||
|
|
||||||
|
use crate::layout::CellStyle;
|
||||||
|
|
||||||
|
/// What a text style token draws as: the colour render emits, and the size and cell attributes
|
||||||
|
/// the text engine reads when it shapes the line.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct TextStyle {
|
||||||
|
pub color: Rgba,
|
||||||
|
pub size: f32,
|
||||||
|
pub cells: CellStyle,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct Theme {
|
||||||
|
pub colors: BTreeMap<String, Rgba>,
|
||||||
|
pub text: BTreeMap<String, TextStyle>,
|
||||||
|
/// Scrollbar thickness, logical px (one cell in Cells).
|
||||||
|
pub scrollbar: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The colour a token the theme does not hold draws as, so the fault is visible.
|
||||||
|
pub fn fallback() -> Rgba {
|
||||||
|
Rgba { r: 0xff, g: 0x00, b: 0xff, a: 0xff }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rgba(hex: u32) -> Rgba {
|
||||||
|
Rgba { r: (hex >> 24) as u8, g: (hex >> 16) as u8, b: (hex >> 8) as u8, a: hex as u8 }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Theme {
|
||||||
|
/// `thing.std`'s default: every token render and the fixtures use.
|
||||||
|
pub fn std() -> Self {
|
||||||
|
let colors = [
|
||||||
|
("thing.surface", 0x1e1e2eff),
|
||||||
|
("thing.error", 0xe5484dff),
|
||||||
|
("thing.placeholder", 0x6e6e80ff),
|
||||||
|
("thing.scrim", 0x00000099),
|
||||||
|
("thing.scrollbar.thumb", 0xffffff66),
|
||||||
|
("thing.control.fill", 0x2c2c3eff),
|
||||||
|
("thing.control.border", 0x4a4a60ff),
|
||||||
|
("thing.control.accent", 0x7c9cffff),
|
||||||
|
("thing.control.text", 0xeeeef4ff),
|
||||||
|
("thing.control.disabled", 0x3a3a48ff),
|
||||||
|
("thing.plot.mark", 0x7c9cffff),
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.map(|(name, hex)| (name.to_string(), rgba(hex)))
|
||||||
|
.collect();
|
||||||
|
let style = |hex: u32, size: f32, bold: bool| TextStyle {
|
||||||
|
color: rgba(hex),
|
||||||
|
size,
|
||||||
|
cells: CellStyle { bold, ..CellStyle::default() },
|
||||||
|
};
|
||||||
|
let text = [
|
||||||
|
("title", style(0xffffffff, 24.0, true)),
|
||||||
|
("body", style(0xeeeef4ff, 16.0, false)),
|
||||||
|
("thing.text", style(0xeeeef4ff, 16.0, false)),
|
||||||
|
("thing.text.placeholder", style(0x6e6e80ff, 16.0, false)),
|
||||||
|
]
|
||||||
|
.into_iter()
|
||||||
|
.map(|(name, style)| (name.to_string(), style))
|
||||||
|
.collect();
|
||||||
|
Self { colors, text, scrollbar: 6.0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The literal a colour is: a token the theme holds, or the literal itself. `None` is an
|
||||||
|
/// unknown token.
|
||||||
|
pub fn resolve(&self, color: &ColorRef) -> Option<Rgba> {
|
||||||
|
match color {
|
||||||
|
ColorRef::Rgba(literal) => Some(literal.clone()),
|
||||||
|
ColorRef::Token(token) => self.colors.get(&token.name).cloned(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A named colour of the theme's own (render's scrim, error and thumb).
|
||||||
|
pub fn color(&self, name: &str) -> Option<Rgba> {
|
||||||
|
self.colors.get(name).cloned()
|
||||||
|
}
|
||||||
|
}
|
||||||
36
crates/thing-core/src/time.rs
Normal file
36
crates/thing-core/src/time.rs
Normal file
|
|
@ -0,0 +1,36 @@
|
||||||
|
//! Wall time as core is told it: the host reads its clock and hands core the reading.
|
||||||
|
|
||||||
|
/// Unix milliseconds, UTC.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
|
pub struct Timestamp(pub i64);
|
||||||
|
|
||||||
|
impl Timestamp {
|
||||||
|
/// This instant plus `ms` milliseconds, saturating.
|
||||||
|
pub fn plus_ms(self, ms: u32) -> Timestamp {
|
||||||
|
Timestamp(self.0.saturating_add(i64::from(ms)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// RFC 3339 in UTC to whole seconds (an instant inside a second is floored), as
|
||||||
|
/// `2026-01-01T00:00:00Z`. The civil date comes from days since 1970-01-01 by Hinnant's
|
||||||
|
/// `civil_from_days`, valid for every date this type holds in the proleptic Gregorian calendar.
|
||||||
|
pub fn rfc3339(self) -> String {
|
||||||
|
let seconds = self.0.div_euclid(1000);
|
||||||
|
let days = seconds.div_euclid(86_400);
|
||||||
|
let in_day = seconds.rem_euclid(86_400);
|
||||||
|
let z = days + 719_468;
|
||||||
|
let era = z.div_euclid(146_097);
|
||||||
|
let day_of_era = z.rem_euclid(146_097);
|
||||||
|
let year_of_era = (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
|
||||||
|
let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
|
||||||
|
let shifted_month = (5 * day_of_year + 2) / 153;
|
||||||
|
let day = day_of_year - (153 * shifted_month + 2) / 5 + 1;
|
||||||
|
let month = if shifted_month < 10 { shifted_month + 3 } else { shifted_month - 9 };
|
||||||
|
let year = year_of_era + era * 400 + i64::from(month <= 2);
|
||||||
|
format!(
|
||||||
|
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
|
||||||
|
in_day / 3600,
|
||||||
|
in_day % 3600 / 60,
|
||||||
|
in_day % 60
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
1089
crates/thing-core/tests/bind.rs
Normal file
1089
crates/thing-core/tests/bind.rs
Normal file
File diff suppressed because it is too large
Load diff
260
crates/thing-core/tests/cells.rs
Normal file
260
crates/thing-core/tests/cells.rs
Normal file
|
|
@ -0,0 +1,260 @@
|
||||||
|
//! The Cells text engine: pinned widths, sanitizing, wrapping, and that `measure` and `text`
|
||||||
|
//! agree. Vectors were checked against unicode-width 0.2.3 (ambiguous width narrow).
|
||||||
|
|
||||||
|
use thing_contract::{AssetEntry, NodeId};
|
||||||
|
use thing_core::bind::Bound;
|
||||||
|
use thing_core::layout::{Avail, Constraint, Leaf, Measure, Run, TextRequest};
|
||||||
|
use thing_core::text::{CellMeasure, CellText};
|
||||||
|
use thing_testkit::build::count;
|
||||||
|
|
||||||
|
fn widths(s: &str) -> Vec<u8> {
|
||||||
|
CellText::new(s).clusters().map(|(_, w)| w).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn width_vectors() {
|
||||||
|
let vectors: &[(&str, &[u8])] = &[
|
||||||
|
("a", &[1]),
|
||||||
|
("\u{4e2d}", &[2]),
|
||||||
|
("\u{ff21}", &[2]),
|
||||||
|
("\u{d55c}", &[2]),
|
||||||
|
("e\u{301}", &[1]),
|
||||||
|
("\u{b1}", &[1]),
|
||||||
|
("\u{3b1}", &[1]),
|
||||||
|
("\u{1f600}", &[2]),
|
||||||
|
("\u{2764}", &[1]),
|
||||||
|
("\u{2764}\u{fe0f}", &[2]),
|
||||||
|
("\u{263a}\u{fe0e}", &[1]),
|
||||||
|
("\u{1f44d}\u{1f3fd}", &[2]),
|
||||||
|
("\u{1f468}\u{200d}\u{1f469}\u{200d}\u{1f467}", &[2]),
|
||||||
|
("\u{1f1ef}\u{1f1f5}", &[2]),
|
||||||
|
("\u{1f1ef}", &[1]),
|
||||||
|
("1\u{fe0f}\u{20e3}", &[2]),
|
||||||
|
("\u{1f3f3}\u{fe0f}\u{200d}\u{1f308}", &[2]),
|
||||||
|
("\u{1100}\u{1161}\u{11a8}", &[2]),
|
||||||
|
("\u{915}\u{94d}\u{937}", &[2]),
|
||||||
|
("\u{e01}\u{e33}", &[2]),
|
||||||
|
("\u{17d8}", &[3]),
|
||||||
|
("\u{a0}", &[1]),
|
||||||
|
("\u{644}\u{627}", &[1, 1]),
|
||||||
|
];
|
||||||
|
for (text, expected) in vectors {
|
||||||
|
assert_eq!(&widths(text), expected, "{text:?}");
|
||||||
|
assert_eq!(CellText::new(text).width(), expected.iter().map(|&w| u32::from(w)).sum::<u32>(), "{text:?} line width is the cluster sum");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sanitizing() {
|
||||||
|
for c in ['\u{1b}', '\u{7f}', '\u{9b}'] {
|
||||||
|
let s = c.to_string();
|
||||||
|
assert_eq!((CellText::new(&s).as_str(), widths(&s)), ("\u{fffd}", vec![1]), "{c:?}");
|
||||||
|
}
|
||||||
|
assert_eq!(CellText::new("a\tb").as_str(), "a b");
|
||||||
|
assert_eq!(CellText::new("abcdefgh\ti").as_str(), "abcdefgh i");
|
||||||
|
for vanishing in ["\u{202e}", "\u{200b}", "\u{ad}", "\u{200d}", "\u{301}"] {
|
||||||
|
assert_eq!(CellText::new(vanishing).as_str(), "", "{vanishing:?}");
|
||||||
|
}
|
||||||
|
assert_eq!(CellText::new("\u{301}a").as_str(), "a");
|
||||||
|
assert_eq!(CellText::new("x\u{200b}y").as_str(), "xy");
|
||||||
|
// The break opportunity of a dropped cluster survives.
|
||||||
|
assert_eq!(lines("x\u{200b}y", 1), ["x", "y"]);
|
||||||
|
// A terminator handed straight to `new` is a control like any other.
|
||||||
|
assert_eq!(CellText::new("a\nb").as_str(), "a\u{fffd}b");
|
||||||
|
assert_eq!(CellText::new("a\u{2028}b").as_str(), "a\u{fffd}b");
|
||||||
|
assert_eq!(widths("a\u{2028}b"), [1, 1, 1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn dropping_a_cluster_is_measured_after_the_drop() {
|
||||||
|
// woman, a dropped bidi control, skin tone: the terminal sees one 2-wide cluster.
|
||||||
|
let t = CellText::new("\u{1f469}\u{202c}\u{1f3fd}");
|
||||||
|
assert_eq!(t.as_str(), "\u{1f469}\u{1f3fd}");
|
||||||
|
assert_eq!(t.clusters().map(|(_, w)| w).collect::<Vec<_>>(), [2]);
|
||||||
|
// A control turned U+FFFD leaves the mark after it orphaned, and an orphan is dropped.
|
||||||
|
assert_eq!(CellText::new("\u{1b}\u{301}").as_str(), "\u{fffd}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tabs_stop_at_eight_from_the_start_of_the_line() {
|
||||||
|
assert_eq!(CellText::new("\t").as_str(), " ".repeat(8));
|
||||||
|
assert_eq!(CellText::new("\t\t").as_str(), " ".repeat(16));
|
||||||
|
assert_eq!(CellText::new("abcdefgh\t").as_str(), format!("abcdefgh{}", " ".repeat(8)));
|
||||||
|
assert_eq!(CellText::new("abc\t\td").as_str(), format!("abc{}d", " ".repeat(13)));
|
||||||
|
assert_eq!(CellText::new("\u{4e2d}\tx").as_str(), format!("\u{4e2d}{}x", " ".repeat(6)));
|
||||||
|
// After a soft break the stop counts from the wrapped line, not the paragraph.
|
||||||
|
assert_eq!(lines("aaaaaaaa bb\tc", 9), ["aaaaaaaa", "bb c"]);
|
||||||
|
// A tab is a space: it hangs at a soft break.
|
||||||
|
assert_eq!(lines("abcdef\tgh", 7), ["abcdef", "gh"]);
|
||||||
|
assert_eq!(lines("ab cd", 9), ["ab", "cd"]);
|
||||||
|
assert_eq!(lines("ab cd", 10), ["ab cd"]);
|
||||||
|
assert_eq!(leaf_measure("a b", true, None, Avail::MinContent).0, 1.0);
|
||||||
|
assert_eq!(leaf_measure("a b", false, None, Avail::MaxContent).0, 9.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn width_zero_is_one_cluster_per_line() {
|
||||||
|
assert_eq!(lines("abc", 0), ["a", "b", "c"]);
|
||||||
|
assert_eq!(lines("a b", 0), ["a", "b"]);
|
||||||
|
assert_eq!(lines("\u{4e2d}x", 0), ["\u{4e2d}", "x"]);
|
||||||
|
assert_eq!(lines(" a", 2), [" ", "a"]);
|
||||||
|
assert_eq!(layout_lines("abc", true, None, -3.0), ["a", "b", "c"]);
|
||||||
|
assert_eq!(layout_lines("abc", true, None, f32::NAN), ["a", "b", "c"]);
|
||||||
|
assert_eq!(leaf_measure("abc", true, None, Avail::Definite(0.0)), (1.0, 3.0));
|
||||||
|
assert!(lines("abc def", 0).iter().all(|l| !l.is_empty()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_scalar_is_clean() {
|
||||||
|
for c in (0..=char::MAX as u32).filter_map(char::from_u32) {
|
||||||
|
let t = CellText::new(&c.to_string());
|
||||||
|
assert!(!t.as_str().chars().any(|c| c.is_control()), "{:#x}", c as u32);
|
||||||
|
assert!(t.clusters().all(|(_, w)| (1..=3).contains(&w)), "{:#x}", c as u32);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn leaf_measure(text: &str, wrap: bool, max_lines: Option<u32>, room: Avail) -> (f32, f32) {
|
||||||
|
let node = NodeId::new("n");
|
||||||
|
let content = Bound::Text(text.to_string());
|
||||||
|
let leaf = Leaf::Text { node: &node, content: &content, style_token: "body", wrap, max_lines };
|
||||||
|
CellMeasure.measure(&leaf, Constraint { known: [None, None], available: [room, Avail::MaxContent] })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn layout_lines(text: &str, wrap: bool, max_lines: Option<u32>, width: f32) -> Vec<String> {
|
||||||
|
let node = NodeId::new("n");
|
||||||
|
let request = TextRequest { node: &node, text, style_token: "body", wrap, max_lines };
|
||||||
|
CellMeasure
|
||||||
|
.text(&request, width)
|
||||||
|
.lines
|
||||||
|
.into_iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(row, line)| {
|
||||||
|
assert_eq!((line.y, line.height), (row as f32, 1.0));
|
||||||
|
match line.run {
|
||||||
|
Run::Cells { text, .. } => text.as_str().to_string(),
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lines(text: &str, width: u32) -> Vec<String> {
|
||||||
|
layout_lines(text, true, None, width as f32)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wrap_table() {
|
||||||
|
assert_eq!(lines("hello world", 5), ["hello", "world"]);
|
||||||
|
assert_eq!(lines("hello world", 11), ["hello world"]);
|
||||||
|
let han = "\u{4e2d}\u{6587}\u{6587}\u{5b57}";
|
||||||
|
assert_eq!(lines(han, 5), ["\u{4e2d}\u{6587}", "\u{6587}\u{5b57}"]);
|
||||||
|
assert_eq!(lines(han, 3).len(), 4);
|
||||||
|
assert_eq!(lines("\u{4e2d}", 1), ["\u{4e2d}"]);
|
||||||
|
assert_eq!(leaf_measure("\u{4e2d}", true, None, Avail::Definite(1.0)), (2.0, 1.0));
|
||||||
|
assert_eq!(lines("abcdefgh", 3), ["abc", "def", "gh"]);
|
||||||
|
assert_eq!(layout_lines("a\nb", false, None, 80.0), ["a", "b"]);
|
||||||
|
assert_eq!(layout_lines("a\r\nb\u{2028}c", true, None, 80.0), ["a", "b", "c"]);
|
||||||
|
assert_eq!(layout_lines("a\nb", true, Some(1), 80.0), ["a"]);
|
||||||
|
assert_eq!(lines("hello world", 5), ["hello", "world"]);
|
||||||
|
assert_eq!(lines("", 5), [""]);
|
||||||
|
assert_eq!(lines("a\n\nb", 5), ["a", "", "b"]);
|
||||||
|
assert_eq!(lines("a\n", 5), ["a"]);
|
||||||
|
// A break opportunity that falls before a dropped mark (LRM here) is kept for the next cluster.
|
||||||
|
assert_eq!(lines("a \u{200e}bcd", 3), ["a", "bcd"]);
|
||||||
|
// A cluster never splits, however narrow the room.
|
||||||
|
assert_eq!(lines("\u{1f468}\u{200d}\u{1f469}", 1), ["\u{1f468}\u{200d}\u{1f469}"]);
|
||||||
|
assert_eq!(lines("e\u{301}e\u{301}", 1), ["e\u{301}", "e\u{301}"]);
|
||||||
|
assert_eq!(leaf_measure("hello world", true, None, Avail::MinContent).0, 5.0);
|
||||||
|
assert_eq!(leaf_measure("a\nbcd", true, None, Avail::MaxContent).0, 3.0);
|
||||||
|
assert_eq!(leaf_measure("a\nbcd", false, None, Avail::MinContent), (3.0, 2.0));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn measure_agrees_with_text() {
|
||||||
|
let rows: &[(&str, bool, Option<u32>, u32)] = &[
|
||||||
|
("hello world", true, None, 5),
|
||||||
|
("hello world", true, None, 11),
|
||||||
|
("\u{4e2d}\u{6587}\u{6587}\u{5b57}", true, None, 5),
|
||||||
|
("\u{4e2d}\u{6587}\u{6587}\u{5b57}", true, None, 3),
|
||||||
|
("\u{4e2d}", true, None, 1),
|
||||||
|
("abcdefgh", true, None, 3),
|
||||||
|
("a\nb", false, None, 80),
|
||||||
|
("a\nb", true, Some(1), 80),
|
||||||
|
("one two three\tfour five", true, Some(3), 7),
|
||||||
|
("\u{1f469}\u{200d}\u{1f469} x \u{1f600}\u{1f600}\u{1f600}", true, None, 4),
|
||||||
|
("", true, None, 4),
|
||||||
|
];
|
||||||
|
for &(text, wrap, max_lines, width) in rows {
|
||||||
|
let laid = layout_lines(text, wrap, max_lines, width as f32);
|
||||||
|
let (w, h) = leaf_measure(text, wrap, max_lines, Avail::Definite(width as f32));
|
||||||
|
let widest = laid.iter().map(|l| CellText::new(l).width()).max().unwrap_or(0);
|
||||||
|
assert_eq!((w, h), (widest as f32, laid.len() as f32), "{text:?} at {width}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn controls_have_shipped_sizes() {
|
||||||
|
let node = NodeId::new("n");
|
||||||
|
let text = Bound::Text(String::new());
|
||||||
|
let c = Constraint { known: [None, None], available: [Avail::MaxContent, Avail::MaxContent] };
|
||||||
|
let mut m = CellMeasure;
|
||||||
|
assert_eq!(m.measure(&Leaf::TextInput { node: &node, multiline: false, placeholder: &text, value: &text }, c), (25.0, 1.0));
|
||||||
|
assert_eq!(m.measure(&Leaf::TextInput { node: &node, multiline: true, placeholder: &text, value: &text }, c), (25.0, 3.0));
|
||||||
|
assert_eq!(m.measure(&Leaf::Toggle { node: &node }, c), (5.0, 1.0));
|
||||||
|
assert_eq!(m.measure(&Leaf::Slider { node: &node }, c), (20.0, 1.0));
|
||||||
|
assert_eq!(m.measure(&Leaf::Select { node: &node, selected: &text }, c), (20.0, 1.0));
|
||||||
|
assert_eq!(m.measure(&Leaf::Image { node: &node, asset: &Bound::Absent }, c), (0.0, 0.0));
|
||||||
|
let entry = AssetEntry { id: "a".into(), media_type: "image/png".into(), uri: "asset://a".into(), width: count(17), height: count(33) };
|
||||||
|
assert_eq!(m.measure(&Leaf::Image { node: &node, asset: &Bound::Asset(entry) }, c), (3.0, 3.0), "extent over (8, 16), rounded up");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Random strings, every control among them, never panic and never put a control character into
|
||||||
|
/// any line at any width.
|
||||||
|
#[test]
|
||||||
|
fn fuzz_never_emits_a_control() {
|
||||||
|
let mut seed = 0x9e37_79b9_7f4a_7c15_u64;
|
||||||
|
let mut next = move || {
|
||||||
|
seed ^= seed << 13;
|
||||||
|
seed ^= seed >> 7;
|
||||||
|
seed ^= seed << 17;
|
||||||
|
seed
|
||||||
|
};
|
||||||
|
let pool: Vec<char> = (0u32..0x20)
|
||||||
|
.chain(0x7f..0xa0)
|
||||||
|
.chain([0x2028, 0x2029, 0x200b, 0x200d, 0xfe0f, 0x301, 0x20, 0x9, 0x4e2d, 0x1f600, 0x1f469, 0x1f3fd, 0x202c, 0x1f1ef, 0x1f1f5, 0x600, 0x20e3])
|
||||||
|
.filter_map(char::from_u32)
|
||||||
|
.collect();
|
||||||
|
for round in 0..400_000 {
|
||||||
|
let text: String = if round % 4 == 0 {
|
||||||
|
// Raw bytes, so truncated and surrogate encodings become U+FFFD.
|
||||||
|
let bytes: Vec<u8> = (0..(next() % 40)).map(|_| next() as u8).collect();
|
||||||
|
String::from_utf8_lossy(&bytes).into_owned()
|
||||||
|
} else {
|
||||||
|
(0..(next() % 40))
|
||||||
|
.map(|_| match next() % 3 {
|
||||||
|
0 => pool[(next() % pool.len() as u64) as usize],
|
||||||
|
1 => char::from_u32((next() % 0x30000) as u32).unwrap_or('\u{fffd}'),
|
||||||
|
_ => char::from(b'a' + (next() % 26) as u8),
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
};
|
||||||
|
let width = (next() % 12) as f32;
|
||||||
|
let wrap = next() % 2 == 0;
|
||||||
|
for line in layout_lines(&text, wrap, None, width) {
|
||||||
|
assert!(!line.chars().any(|c| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}')), "{text:?} -> {line:?}");
|
||||||
|
}
|
||||||
|
// What is emitted measures to what was recorded: measuring it again changes nothing.
|
||||||
|
let node = NodeId::new("n");
|
||||||
|
let request = TextRequest { node: &node, text: &text, style_token: "body", wrap, max_lines: None };
|
||||||
|
for line in CellMeasure.text(&request, width).lines {
|
||||||
|
let Run::Cells { text: emitted, .. } = line.run else { panic!() };
|
||||||
|
assert_eq!(CellText::new(emitted.as_str()), emitted, "{text:?} at {width}");
|
||||||
|
assert!(emitted.clusters().all(|(_, w)| w >= 1));
|
||||||
|
}
|
||||||
|
let lone = CellText::new(&text);
|
||||||
|
assert_eq!(CellText::new(lone.as_str()), lone, "{text:?}");
|
||||||
|
let _ = leaf_measure(&text, wrap, Some(3), Avail::Definite(width));
|
||||||
|
let _ = leaf_measure(&text, wrap, None, Avail::MinContent);
|
||||||
|
assert!(!CellText::new(&text).as_str().chars().any(|c| c.is_control()));
|
||||||
|
}
|
||||||
|
}
|
||||||
1444
crates/thing-core/tests/command.rs
Normal file
1444
crates/thing-core/tests/command.rs
Normal file
File diff suppressed because it is too large
Load diff
492
crates/thing-core/tests/frame.rs
Normal file
492
crates/thing-core/tests/frame.rs
Normal file
|
|
@ -0,0 +1,492 @@
|
||||||
|
//! The frame entry: Core::frame equals the stages composed by hand, and keeps its promises
|
||||||
|
//! about the port, the last good frame and the room it is given.
|
||||||
|
|
||||||
|
use thing_contract::*;
|
||||||
|
use thing_core::bind::Binder;
|
||||||
|
use thing_core::diagnostic::Code;
|
||||||
|
use thing_core::input::{InputEvent, Key, Modifiers, PointerButton, WheelUnit};
|
||||||
|
use thing_core::layout::{LayoutFrame, Metrics, layout};
|
||||||
|
use thing_core::port::{Address, Ledger};
|
||||||
|
use thing_core::render::{RenderCommand, RenderInput, ScrollOffsets, Session, render};
|
||||||
|
use thing_core::resolve::{Limits, resolve};
|
||||||
|
use thing_core::theme::Theme;
|
||||||
|
use thing_core::time::Timestamp;
|
||||||
|
use thing_core::{Config, Core, FrameInput, FrameOutput, Ports};
|
||||||
|
use thing_testkit::build::*;
|
||||||
|
use thing_testkit::fixture::Fixture;
|
||||||
|
use thing_testkit::ids::SeqIds;
|
||||||
|
use thing_testkit::measure::FixedMeasure;
|
||||||
|
use thing_testkit::mem_state::{Call, MemState};
|
||||||
|
use thing_testkit::state::{self, Swarm};
|
||||||
|
|
||||||
|
const PROVIDER: &str = "provider.frame";
|
||||||
|
|
||||||
|
fn measure(metrics: Metrics) -> FixedMeasure {
|
||||||
|
match metrics {
|
||||||
|
Metrics::Pixels => FixedMeasure::pixels(),
|
||||||
|
Metrics::Cells => FixedMeasure::cells(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fresh(metrics: Metrics) -> Core {
|
||||||
|
Core::new(Config::new(metrics, "renderer.test"), Box::new(measure(metrics)))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn input(viewport: (f32, f32), scale: f32) -> FrameInput {
|
||||||
|
FrameInput { now: Timestamp(0), viewport, scale, events: vec![] }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(core: &mut Core, state: &mut MemState, input: FrameInput) -> FrameOutput {
|
||||||
|
core.frame(input, Ports { state, ids: &mut SeqIds::new() })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn show(core: &mut Core, document: &SurfaceDocument) {
|
||||||
|
core.show(document.provider_id.clone(), RecordKey::new(document.record_key()));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn world(fixture: Fixture) -> MemState {
|
||||||
|
let mut state = MemState::from_fixture(fixture);
|
||||||
|
state::script(fixture, &mut state);
|
||||||
|
state
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The commands of the stages composed by hand, as tests/render.rs composes them.
|
||||||
|
fn staged(document: &SurfaceDocument, state: &mut MemState, viewport: (f32, f32), scale: f32, metrics: Metrics) -> Vec<RenderCommand> {
|
||||||
|
let limits = Limits::default();
|
||||||
|
let tree = resolve(document, state, &limits).tree.expect("resolves");
|
||||||
|
let mut binder = Binder::new(limits);
|
||||||
|
binder.bind(tree, state, &mut Ledger::new());
|
||||||
|
let bound = binder.tree(&document.record_key()).expect("bound");
|
||||||
|
let frame = LayoutFrame { viewport, scale, metrics };
|
||||||
|
let laid = layout(bound, &frame, &mut measure(metrics)).unwrap();
|
||||||
|
let scroll = ScrollOffsets::default();
|
||||||
|
let theme = Theme::std();
|
||||||
|
let input = RenderInput { scale, metrics, viewport, scroll: &scroll, theme: &theme, session: Session::EMPTY };
|
||||||
|
render(bound, &laid, &input, &mut measure(metrics)).commands
|
||||||
|
}
|
||||||
|
|
||||||
|
fn inline(version: i64, root: Node) -> SurfaceDocument {
|
||||||
|
SurfaceDocument {
|
||||||
|
provider_id: ProviderId::new(PROVIDER),
|
||||||
|
label: seg("main"),
|
||||||
|
version: ver(version),
|
||||||
|
title: "frame".into(),
|
||||||
|
root,
|
||||||
|
commands: vec![],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn say(version: i64, words: &str) -> SurfaceDocument {
|
||||||
|
inline(version, boxed("root", vec![text("words", words)]))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn surface_address(document: &SurfaceDocument) -> Address {
|
||||||
|
Address {
|
||||||
|
provider: document.provider_id.clone(),
|
||||||
|
schema: SchemaId::new(SurfaceDocument::SCHEMA_NAME),
|
||||||
|
key: RecordKey::new(document.record_key()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn codes(output: &FrameOutput) -> Vec<Code> {
|
||||||
|
output.diagnostics.iter().map(|diagnostic| diagnostic.code).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn count(state: &MemState, wanted: impl Fn(&Call) -> bool) -> usize {
|
||||||
|
state.calls().iter().filter(|call| wanted(call)).count()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pipeline_equals_the_stages() {
|
||||||
|
let cells = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
|
||||||
|
let mut state = world(Fixture::F01SwarmDashboard);
|
||||||
|
let mut one = fresh(Metrics::Cells);
|
||||||
|
show(&mut one, &cells);
|
||||||
|
let output = run(&mut one, &mut state, input((100.0, 37.0), 1.0));
|
||||||
|
let expected = staged(&cells, &mut world(Fixture::F01SwarmDashboard), (100.0, 37.0), 1.0, Metrics::Cells);
|
||||||
|
assert!(!expected.is_empty());
|
||||||
|
assert_eq!(output.commands, expected);
|
||||||
|
assert_eq!(output.next_wake, None);
|
||||||
|
|
||||||
|
let list = Fixture::F06ScrollList.load().surfaces.remove(0);
|
||||||
|
let mut state = world(Fixture::F06ScrollList);
|
||||||
|
let mut two = fresh(Metrics::Pixels);
|
||||||
|
show(&mut two, &list);
|
||||||
|
let output = run(&mut two, &mut state, input((800.0, 600.0), 1.5));
|
||||||
|
let expected = staged(&list, &mut world(Fixture::F06ScrollList), (800.0, 600.0), 1.5, Metrics::Pixels);
|
||||||
|
assert!(!expected.is_empty());
|
||||||
|
assert_eq!(output.commands, expected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_idle_frame_draws_the_same_and_drains_once() {
|
||||||
|
let document = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
|
||||||
|
let mut state = world(Fixture::F01SwarmDashboard);
|
||||||
|
let mut core = fresh(Metrics::Cells);
|
||||||
|
show(&mut core, &document);
|
||||||
|
let first = run(&mut core, &mut state, input((100.0, 37.0), 1.0));
|
||||||
|
assert_eq!(count(&state, |call| *call == Call::Drain), 1);
|
||||||
|
let before = state.calls().len();
|
||||||
|
let second = run(&mut core, &mut state, input((100.0, 37.0), 1.0));
|
||||||
|
assert_eq!(second.commands, first.commands);
|
||||||
|
assert_eq!(state.calls()[before..], [Call::Drain]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn show_holds_the_interest_before_it_reads_and_draws_when_published() {
|
||||||
|
let document = say(1, "hello");
|
||||||
|
let mut state = MemState::new();
|
||||||
|
let mut core = fresh(Metrics::Cells);
|
||||||
|
show(&mut core, &document);
|
||||||
|
let output = run(&mut core, &mut state, input((40.0, 5.0), 1.0));
|
||||||
|
assert_eq!(output.commands, vec![]);
|
||||||
|
assert_eq!(output.diagnostics, vec![]);
|
||||||
|
let address = surface_address(&document);
|
||||||
|
let calls = state.calls();
|
||||||
|
let subscribe = calls.iter().position(|call| matches!(call, Call::Subscribe(interest) if interest.matches(&address))).expect("subscribed");
|
||||||
|
let read = calls.iter().position(|call| *call == Call::Read(address.clone())).expect("read");
|
||||||
|
assert!(subscribe < read, "{calls:?}");
|
||||||
|
|
||||||
|
state.put(&document.provider_id, &document);
|
||||||
|
let output = run(&mut core, &mut state, input((40.0, 5.0), 1.0));
|
||||||
|
assert_eq!(output.commands, staged(&document, &mut MemState::new(), (40.0, 5.0), 1.0, Metrics::Cells));
|
||||||
|
assert!(!output.commands.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_republish_replaces_the_picture_and_a_delete_empties_it() {
|
||||||
|
let v1 = say(1, "first");
|
||||||
|
let v2 = say(2, "second");
|
||||||
|
let mut state = MemState::new();
|
||||||
|
state.put(&v1.provider_id, &v1);
|
||||||
|
let mut core = fresh(Metrics::Cells);
|
||||||
|
show(&mut core, &v1);
|
||||||
|
let at = (40.0, 5.0);
|
||||||
|
let first = run(&mut core, &mut state, input(at, 1.0));
|
||||||
|
assert_eq!(first.commands, staged(&v1, &mut MemState::new(), at, 1.0, Metrics::Cells));
|
||||||
|
|
||||||
|
state.put(&v2.provider_id, &v2);
|
||||||
|
let second = run(&mut core, &mut state, input(at, 1.0));
|
||||||
|
assert_eq!(second.commands, staged(&v2, &mut MemState::new(), at, 1.0, Metrics::Cells));
|
||||||
|
assert_ne!(second.commands, first.commands);
|
||||||
|
assert_eq!(codes(&second), vec![]);
|
||||||
|
|
||||||
|
// The same record delivered again is not news.
|
||||||
|
state.put(&v2.provider_id, &v2);
|
||||||
|
let again = run(&mut core, &mut state, input(at, 1.0));
|
||||||
|
assert_eq!(codes(&again), vec![]);
|
||||||
|
assert_eq!(again.commands, second.commands);
|
||||||
|
|
||||||
|
// A different document at the held version is refused and the held one stays.
|
||||||
|
let other = say(2, "impostor");
|
||||||
|
state.put(&other.provider_id, &other);
|
||||||
|
let stale = run(&mut core, &mut state, input(at, 1.0));
|
||||||
|
assert_eq!(codes(&stale), vec![Code::StaleVersionIgnored]);
|
||||||
|
assert_eq!(stale.commands, second.commands);
|
||||||
|
|
||||||
|
state.delete(&surface_address(&v2));
|
||||||
|
let gone = run(&mut core, &mut state, input(at, 1.0));
|
||||||
|
assert_eq!(gone.commands, vec![]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_changed_state_record_draws_and_a_late_composition_rebinds() {
|
||||||
|
let document = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
|
||||||
|
let mut state = world(Fixture::F01SwarmDashboard);
|
||||||
|
let mut core = fresh(Metrics::Cells);
|
||||||
|
show(&mut core, &document);
|
||||||
|
let at = (100.0, 37.0);
|
||||||
|
let before = run(&mut core, &mut state, input(at, 1.0));
|
||||||
|
|
||||||
|
let summary = Swarm { id: "summary".into(), name: "Swarm".into(), load: 0.93 };
|
||||||
|
state.put_state(&ProviderId::new("provider.swarm"), "summary", &summary);
|
||||||
|
let after = run(&mut core, &mut state, input(at, 1.0));
|
||||||
|
let mut moved = world(Fixture::F01SwarmDashboard);
|
||||||
|
moved.put_state(&ProviderId::new("provider.swarm"), "summary", &summary);
|
||||||
|
assert_eq!(after.commands, staged(&document, &mut moved, at, 1.0, Metrics::Cells));
|
||||||
|
assert_ne!(after.commands, before.commands);
|
||||||
|
|
||||||
|
// f09: the surface is published first and its composition after.
|
||||||
|
let stack = Fixture::F09CompositionStack.load();
|
||||||
|
let surface = stack.surfaces[0].clone();
|
||||||
|
let mut state = MemState::new();
|
||||||
|
state.put(&surface.provider_id, &surface);
|
||||||
|
for (key, record) in state::swarm_records() {
|
||||||
|
state.put_state(&ProviderId::new("provider.stack"), key, &record);
|
||||||
|
}
|
||||||
|
let mut late = fresh(Metrics::Cells);
|
||||||
|
show(&mut late, &surface);
|
||||||
|
let placeholder = run(&mut late, &mut state, input(at, 1.0));
|
||||||
|
assert!(codes(&placeholder).contains(&Code::UnresolvedUse), "{:?}", codes(&placeholder));
|
||||||
|
for composition in &stack.compositions {
|
||||||
|
state.put(&ProviderId::new(composition.publisher.clone()), composition);
|
||||||
|
}
|
||||||
|
let resolved = run(&mut late, &mut state, input(at, 1.0));
|
||||||
|
let mut full = MemState::from_fixture(Fixture::F09CompositionStack);
|
||||||
|
for (key, record) in state::swarm_records() {
|
||||||
|
full.put_state(&ProviderId::new("provider.stack"), key, &record);
|
||||||
|
}
|
||||||
|
assert_eq!(resolved.commands, staged(&surface, &mut full, at, 1.0, Metrics::Cells));
|
||||||
|
assert_ne!(resolved.commands, placeholder.commands);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn no_room_draws_nothing_without_a_diagnostic_and_the_next_frame_draws_again() {
|
||||||
|
let document = say(1, "room");
|
||||||
|
let mut state = MemState::new();
|
||||||
|
state.put(&document.provider_id, &document);
|
||||||
|
let mut core = fresh(Metrics::Cells);
|
||||||
|
show(&mut core, &document);
|
||||||
|
let first = run(&mut core, &mut state, input((40.0, 5.0), 1.0));
|
||||||
|
assert!(!first.commands.is_empty());
|
||||||
|
let cramped = run(&mut core, &mut state, input((0.0, 37.0), 1.0));
|
||||||
|
assert_eq!(cramped.commands, vec![]);
|
||||||
|
assert_eq!(cramped.diagnostics, vec![]);
|
||||||
|
let again = run(&mut core, &mut state, input((40.0, 5.0), 1.0));
|
||||||
|
assert_eq!(again.commands, first.commands);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_layout_past_the_precision_bound_keeps_the_last_good_frame() {
|
||||||
|
let good = say(1, "fits");
|
||||||
|
// Two boxes side by side that together reach past the bound: neither alone is refused.
|
||||||
|
let slab = |id: &str| match boxed(id, vec![]) {
|
||||||
|
Node::Box(mut slab) => {
|
||||||
|
slab.style.size = size2(px(1_500_000.0), px(10.0));
|
||||||
|
Node::Box(slab)
|
||||||
|
}
|
||||||
|
other => other,
|
||||||
|
};
|
||||||
|
let mut wide = inline(2, boxed("root", vec![slab("left"), slab("right")]));
|
||||||
|
if let Node::Box(root) = &mut wide.root {
|
||||||
|
root.style.direction = Direction::Row;
|
||||||
|
}
|
||||||
|
let mut state = MemState::new();
|
||||||
|
state.put(&good.provider_id, &good);
|
||||||
|
let mut core = fresh(Metrics::Pixels);
|
||||||
|
show(&mut core, &good);
|
||||||
|
let first = run(&mut core, &mut state, input((800.0, 600.0), 1.0));
|
||||||
|
assert!(!first.commands.is_empty());
|
||||||
|
state.put(&wide.provider_id, &wide);
|
||||||
|
let refused = run(&mut core, &mut state, input((800.0, 600.0), 1.0));
|
||||||
|
assert_eq!(refused.commands, first.commands);
|
||||||
|
assert_eq!(codes(&refused), vec![Code::LayoutOutOfRange]);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn every_event() -> Vec<InputEvent> {
|
||||||
|
let modifiers = Modifiers { shift: true, ctrl: false, alt: true, meta: false };
|
||||||
|
let at = (3.5, 2.5);
|
||||||
|
vec![
|
||||||
|
InputEvent::Key { key: Key::Char('A'), modifiers, repeat: false },
|
||||||
|
InputEvent::Key { key: Key::F(5), modifiers: Modifiers::default(), repeat: true },
|
||||||
|
InputEvent::Text("hi".into()),
|
||||||
|
InputEvent::Compose { text: "か".into(), cursor: Some((0, 3)) },
|
||||||
|
InputEvent::PointerDown { at, button: PointerButton::Primary, modifiers },
|
||||||
|
InputEvent::PointerMove { at, modifiers },
|
||||||
|
InputEvent::PointerUp { at, button: PointerButton::Primary, modifiers },
|
||||||
|
InputEvent::PointerCancel,
|
||||||
|
InputEvent::Wheel { at, delta: (0.0, 1.0), unit: WheelUnit::Lines, modifiers },
|
||||||
|
InputEvent::Focus(false),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn keys_text_composition_and_focus_change_nothing_yet() {
|
||||||
|
let document = Fixture::F06ScrollList.load().surfaces.remove(0);
|
||||||
|
let at = (800.0, 600.0);
|
||||||
|
let (mut quiet_state, mut busy_state) = (world(Fixture::F06ScrollList), world(Fixture::F06ScrollList));
|
||||||
|
let (mut quiet, mut busy) = (fresh(Metrics::Pixels), fresh(Metrics::Pixels));
|
||||||
|
show(&mut quiet, &document);
|
||||||
|
show(&mut busy, &document);
|
||||||
|
let plain = run(&mut quiet, &mut quiet_state, input(at, 1.0));
|
||||||
|
let mut with_events = input(at, 1.0);
|
||||||
|
// The pointer is routed (tests/input.rs); keys, text, composition and focus are the focus cut's.
|
||||||
|
with_events.events = every_event().into_iter().filter(|event| !matches!(event, InputEvent::PointerDown { .. } | InputEvent::PointerMove { .. } | InputEvent::PointerUp { .. } | InputEvent::PointerCancel | InputEvent::Wheel { .. })).collect();
|
||||||
|
let output = run(&mut busy, &mut busy_state, with_events);
|
||||||
|
assert_eq!(output, plain);
|
||||||
|
assert_eq!(busy_state.calls(), quiet_state.calls());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn showing_another_surface_releases_the_first() {
|
||||||
|
let (a, b) = (say(1, "alpha"), {
|
||||||
|
let mut b = say(1, "beta");
|
||||||
|
b.label = seg("other");
|
||||||
|
b
|
||||||
|
});
|
||||||
|
let mut state = MemState::new();
|
||||||
|
state.put(&a.provider_id, &a);
|
||||||
|
state.put(&b.provider_id, &b);
|
||||||
|
let mut core = fresh(Metrics::Cells);
|
||||||
|
let at = (40.0, 5.0);
|
||||||
|
show(&mut core, &a);
|
||||||
|
let first = run(&mut core, &mut state, input(at, 1.0));
|
||||||
|
assert_eq!(count(&state, |call| matches!(call, Call::Unsubscribe(_))), 0);
|
||||||
|
show(&mut core, &b);
|
||||||
|
let second = run(&mut core, &mut state, input(at, 1.0));
|
||||||
|
assert_eq!(count(&state, |call| matches!(call, Call::Unsubscribe(_))), 1);
|
||||||
|
assert_eq!(second.commands, staged(&b, &mut MemState::new(), at, 1.0, Metrics::Cells));
|
||||||
|
assert_ne!(second.commands, first.commands);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A random box tree: sizes from a hostile list (zero, negative, NaN, past the bound), scroll and
|
||||||
|
/// clip boxes, texts.
|
||||||
|
fn random_node(next: &mut dyn FnMut() -> u64, id: &mut u32, depth: u32) -> Node {
|
||||||
|
let sizes = [0.0, 1.0, 7.5, 40.0, 100.0, 5000.0, 1e6, 1e7, -4.0, f64::NAN];
|
||||||
|
*id += 1;
|
||||||
|
let name = format!("n{id}");
|
||||||
|
if depth == 0 || next() % 4 == 0 {
|
||||||
|
return text(&name, &format!("text {id}"));
|
||||||
|
}
|
||||||
|
let Node::Box(mut node) = boxed(&name, vec![]) else { unreachable!() };
|
||||||
|
node.style.size = size2(px(sizes[(next() % 10) as usize]), px(sizes[(next() % 10) as usize]));
|
||||||
|
node.style.direction = if next() % 2 == 0 { Direction::Row } else { Direction::Column };
|
||||||
|
node.style.overflow = [Overflow::Visible, Overflow::Clip, Overflow::Scroll][(next() % 3) as usize].clone();
|
||||||
|
let children = next() % 4;
|
||||||
|
node.children = (0..children).map(|_| random_node(next, id, depth - 1)).collect();
|
||||||
|
Node::Box(node)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fixed seeds for reproducibility, plus `THING_FRAME_SEED` when set; a failure names its seed.
|
||||||
|
#[test]
|
||||||
|
fn random_documents_and_inputs_never_panic_and_the_frame_is_deterministic() {
|
||||||
|
let mut seeds = vec![0x9E37_79B9_7F4A_7C15u64, 0xD1B5_4A32_D192_ED03, 0x2545_F491_4F6C_DD1D, 7];
|
||||||
|
if let Some(extra) = std::env::var("THING_FRAME_SEED").ok().and_then(|v| v.parse().ok()) {
|
||||||
|
seeds.push(extra);
|
||||||
|
}
|
||||||
|
for seed in seeds {
|
||||||
|
random_run(seed);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn random_run(mut seed: u64) {
|
||||||
|
let mut next = move || {
|
||||||
|
seed ^= seed << 13;
|
||||||
|
seed ^= seed >> 7;
|
||||||
|
seed ^= seed << 17;
|
||||||
|
seed
|
||||||
|
};
|
||||||
|
let rooms = [(100.0, 37.0), (0.0, 0.0), (-5.0, 10.0), (f32::NAN, 4.0), (f32::INFINITY, 4.0), (800.0, 600.0), (1e9, 1e9), (1.0, 1.0)];
|
||||||
|
let scales = [1.0, 1.5, 0.0, -1.0, f32::NAN, f32::INFINITY, 1e6, 2.0];
|
||||||
|
for metrics in [Metrics::Pixels, Metrics::Cells] {
|
||||||
|
let (mut left, mut right) = (fresh(metrics), fresh(metrics));
|
||||||
|
let (mut left_state, mut right_state) = (MemState::new(), MemState::new());
|
||||||
|
let mut shown = false;
|
||||||
|
for round in 0..200i64 {
|
||||||
|
if next() % 9 != 0 {
|
||||||
|
let mut id = 0;
|
||||||
|
let document = inline(round + 1, random_node(&mut next, &mut id, 4));
|
||||||
|
if !shown {
|
||||||
|
show(&mut left, &document);
|
||||||
|
show(&mut right, &document);
|
||||||
|
shown = true;
|
||||||
|
}
|
||||||
|
left_state.put(&document.provider_id, &document);
|
||||||
|
right_state.put(&document.provider_id, &document);
|
||||||
|
} else if shown {
|
||||||
|
let address = surface_address(&inline(1, boxed("root", vec![])));
|
||||||
|
left_state.delete(&address);
|
||||||
|
right_state.delete(&address);
|
||||||
|
}
|
||||||
|
let room = rooms[(next() % 8) as usize];
|
||||||
|
let scale = scales[(next() % 8) as usize];
|
||||||
|
let events = every_event().into_iter().take((next() % 11) as usize).collect::<Vec<_>>();
|
||||||
|
let frame = FrameInput { now: Timestamp(round), viewport: room, scale, events };
|
||||||
|
let one = run(&mut left, &mut left_state, frame.clone());
|
||||||
|
let two = run(&mut right, &mut right_state, frame);
|
||||||
|
assert_eq!(one, two, "seed {seed} round {round} in {metrics:?} at {room:?} scale {scale}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wide(version: i64) -> SurfaceDocument {
|
||||||
|
let slab = |id: &str| match boxed(id, vec![]) {
|
||||||
|
Node::Box(mut slab) => {
|
||||||
|
slab.style.size = size2(px(1_500_000.0), px(10.0));
|
||||||
|
Node::Box(slab)
|
||||||
|
}
|
||||||
|
other => other,
|
||||||
|
};
|
||||||
|
let mut document = inline(version, boxed("root", vec![slab("left"), slab("right")]));
|
||||||
|
if let Node::Box(root) = &mut document.root {
|
||||||
|
root.style.direction = Direction::Row;
|
||||||
|
}
|
||||||
|
document
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_last_good_frame_is_cleared_by_a_delete_and_a_switch_and_kept_through_a_frame_error() {
|
||||||
|
let at = (800.0, 600.0);
|
||||||
|
let good = say(1, "fits");
|
||||||
|
// Kept through a room with no size: a refused layout afterwards still shows it.
|
||||||
|
let mut state = MemState::new();
|
||||||
|
state.put(&good.provider_id, &good);
|
||||||
|
let mut one = fresh(Metrics::Pixels);
|
||||||
|
show(&mut one, &good);
|
||||||
|
let first = run(&mut one, &mut state, input(at, 1.0));
|
||||||
|
run(&mut one, &mut state, input((f32::NAN, 600.0), 1.0));
|
||||||
|
state.put(&good.provider_id, &wide(2));
|
||||||
|
let held = run(&mut one, &mut state, input(at, 1.0));
|
||||||
|
assert_eq!(held.commands, first.commands);
|
||||||
|
assert_eq!(codes(&held), vec![Code::LayoutOutOfRange]);
|
||||||
|
|
||||||
|
// Cleared by a delete: what comes after has no frame to fall back on.
|
||||||
|
let mut state = MemState::new();
|
||||||
|
state.put(&good.provider_id, &good);
|
||||||
|
let mut two = fresh(Metrics::Pixels);
|
||||||
|
show(&mut two, &good);
|
||||||
|
run(&mut two, &mut state, input(at, 1.0));
|
||||||
|
state.delete(&surface_address(&good));
|
||||||
|
assert_eq!(run(&mut two, &mut state, input(at, 1.0)).commands, vec![]);
|
||||||
|
// The tombstone keeps the version: the same document again, and a different one at it, change nothing shown.
|
||||||
|
state.put(&good.provider_id, &good);
|
||||||
|
let replay = run(&mut two, &mut state, input(at, 1.0));
|
||||||
|
assert_eq!((codes(&replay), replay.commands), (vec![], vec![]));
|
||||||
|
state.put(&good.provider_id, &say(1, "other"));
|
||||||
|
let refused = run(&mut two, &mut state, input(at, 1.0));
|
||||||
|
assert_eq!((codes(&refused), refused.commands), (vec![Code::StaleVersionIgnored], vec![]));
|
||||||
|
state.put(&good.provider_id, &wide(2));
|
||||||
|
let out = run(&mut two, &mut state, input(at, 1.0));
|
||||||
|
assert_eq!((codes(&out), out.commands), (vec![Code::LayoutOutOfRange], vec![]));
|
||||||
|
|
||||||
|
// Cleared by a switch.
|
||||||
|
let other = {
|
||||||
|
let mut other = wide(1);
|
||||||
|
other.label = seg("other");
|
||||||
|
other
|
||||||
|
};
|
||||||
|
let mut state = MemState::new();
|
||||||
|
state.put(&good.provider_id, &good);
|
||||||
|
state.put(&other.provider_id, &other);
|
||||||
|
let mut three = fresh(Metrics::Pixels);
|
||||||
|
show(&mut three, &good);
|
||||||
|
run(&mut three, &mut state, input(at, 1.0));
|
||||||
|
show(&mut three, &other);
|
||||||
|
let switched = run(&mut three, &mut state, input(at, 1.0));
|
||||||
|
assert_eq!((codes(&switched), switched.commands), (vec![Code::LayoutOutOfRange], vec![]));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_switch_leaves_the_old_surface_holding_no_interest() {
|
||||||
|
let swarm = Fixture::F01SwarmDashboard.load().surfaces.remove(0);
|
||||||
|
let other = say(1, "elsewhere");
|
||||||
|
let mut state = world(Fixture::F01SwarmDashboard);
|
||||||
|
state.put(&other.provider_id, &other);
|
||||||
|
let mut core = fresh(Metrics::Cells);
|
||||||
|
let at = (100.0, 37.0);
|
||||||
|
show(&mut core, &swarm);
|
||||||
|
run(&mut core, &mut state, input(at, 1.0));
|
||||||
|
let subscribed = count(&state, |call| matches!(call, Call::Subscribe(_)));
|
||||||
|
assert!(subscribed > 1, "f01 binds provider state, so more than its own record is held");
|
||||||
|
show(&mut core, &other);
|
||||||
|
run(&mut core, &mut state, input(at, 1.0));
|
||||||
|
let subscribes = count(&state, |call| matches!(call, Call::Subscribe(_)));
|
||||||
|
let unsubscribes = count(&state, |call| matches!(call, Call::Unsubscribe(_)));
|
||||||
|
assert_eq!(subscribes - unsubscribes, 1, "only the shown surface's own record is held");
|
||||||
|
// A record the old surface read now changes nothing and costs no read.
|
||||||
|
let summary = Swarm { id: "summary".into(), name: "Swarm".into(), load: 0.5 };
|
||||||
|
state.put_state(&ProviderId::new("provider.swarm"), "summary", &summary);
|
||||||
|
let before = state.calls().len();
|
||||||
|
run(&mut core, &mut state, input(at, 1.0));
|
||||||
|
assert_eq!(state.calls()[before..], [Call::Drain]);
|
||||||
|
}
|
||||||
6
crates/thing-core/tests/goldens/README.md
Normal file
6
crates/thing-core/tests/goldens/README.md
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
# thing-core goldens
|
||||||
|
|
||||||
|
`resolve-*.bin` is a CultCache single-file store holding one resolved surface document under the
|
||||||
|
pinned clock; `resolve-*.txt` is the `{:#?}` text of the same document. The binary is the oracle and
|
||||||
|
the text is compared beside it. `THING_BLESS=1` through `thing_testkit::golden::check_with_text` is
|
||||||
|
the only way either changes.
|
||||||
14
crates/thing-core/tests/goldens/bind-f01-swarm-dashboard.txt
Normal file
14
crates/thing-core/tests/goldens/bind-f01-swarm-dashboard.txt
Normal file
|
|
@ -0,0 +1,14 @@
|
||||||
|
load visible bool true
|
||||||
|
load content text "42.0%"
|
||||||
|
minds visible bool true
|
||||||
|
minds#6:mind-1/mind-name visible bool true
|
||||||
|
minds#6:mind-1/mind-name content text "Eureka"
|
||||||
|
minds#6:mind-2/mind-name visible bool true
|
||||||
|
minds#6:mind-2/mind-name content text "Libby"
|
||||||
|
minds#6:mind-3/mind-name visible bool true
|
||||||
|
minds#6:mind-3/mind-name content text "Kiko"
|
||||||
|
restart visible bool true
|
||||||
|
restart enabled bool true
|
||||||
|
restart-label visible bool true
|
||||||
|
restart-label content text "Restart"
|
||||||
|
root visible bool true
|
||||||
11
crates/thing-core/tests/goldens/bind-f04-form.txt
Normal file
11
crates/thing-core/tests/goldens/bind-f04-form.txt
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
enabled visible bool true
|
||||||
|
enabled checked bool true
|
||||||
|
port visible bool true
|
||||||
|
port placeholder text "port"
|
||||||
|
port initial text "8080"
|
||||||
|
root visible bool true
|
||||||
|
theme visible bool true
|
||||||
|
theme selected text "dark"
|
||||||
|
theme options options [dark=Dark, light=Light]
|
||||||
|
volume visible bool true
|
||||||
|
volume value number 40
|
||||||
|
|
@ -0,0 +1,8 @@
|
||||||
|
surface thing:surface:provider.swarm.dashboard viewport 100x37 scale 1 cells
|
||||||
|
root 0 0 100 6
|
||||||
|
load 0 0 50 1
|
||||||
|
minds#6:mind-1/mind-name 51 0 49 1
|
||||||
|
minds#6:mind-2/mind-name 0 2 50 1
|
||||||
|
minds#6:mind-3/mind-name 51 2 49 1
|
||||||
|
restart 0 3 50 3
|
||||||
|
restart-label 1 4 7 1
|
||||||
|
|
@ -0,0 +1,8 @@
|
||||||
|
surface thing:surface:provider.swarm.dashboard viewport 800x600 scale 1.5 pixels
|
||||||
|
root 0 0 1200 102
|
||||||
|
load 3 3 597 24
|
||||||
|
minds#6:mind-1/mind-name 606 3 597 24
|
||||||
|
minds#6:mind-2/mind-name 3 39 597 24
|
||||||
|
minds#6:mind-3/mind-name 606 39 597 24
|
||||||
|
restart 3 75 597 24
|
||||||
|
restart-label 3 75 84 24
|
||||||
|
|
@ -0,0 +1,8 @@
|
||||||
|
surface thing:surface:provider.swarm.dashboard viewport 800x600 scale 2 pixels
|
||||||
|
root 0 0 1600 136
|
||||||
|
load 4 4 796 32
|
||||||
|
minds#6:mind-1/mind-name 808 4 796 32
|
||||||
|
minds#6:mind-2/mind-name 4 52 796 32
|
||||||
|
minds#6:mind-3/mind-name 808 52 796 32
|
||||||
|
restart 4 100 796 32
|
||||||
|
restart-label 4 100 112 32
|
||||||
|
|
@ -0,0 +1,8 @@
|
||||||
|
surface thing:surface:provider.swarm.dashboard viewport 800x600 scale 1 pixels
|
||||||
|
root 0 0 800 68
|
||||||
|
load 2 2 398 16
|
||||||
|
minds#6:mind-1/mind-name 404 2 398 16
|
||||||
|
minds#6:mind-2/mind-name 2 26 398 16
|
||||||
|
minds#6:mind-3/mind-name 404 26 398 16
|
||||||
|
restart 2 50 398 16
|
||||||
|
restart-label 2 50 56 16
|
||||||
|
|
@ -0,0 +1,5 @@
|
||||||
|
surface thing:surface:provider.login.login viewport 800x600 scale 1 pixels
|
||||||
|
root 0 0 800 52
|
||||||
|
username 2 2 796 24
|
||||||
|
sign-in-button 2 34 796 16
|
||||||
|
sign-in-button-label 2 34 56 16
|
||||||
|
|
@ -0,0 +1,5 @@
|
||||||
|
surface thing:surface:provider.muninn.input-target viewport 800x600 scale 1 pixels
|
||||||
|
root 80 0 640 360
|
||||||
|
board 82 2 636 360
|
||||||
|
target 280 120 48 48
|
||||||
|
target-label 282 122 44 16
|
||||||
6
crates/thing-core/tests/goldens/layout-f04-form.txt
Normal file
6
crates/thing-core/tests/goldens/layout-f04-form.txt
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
surface thing:surface:provider.settings.form viewport 800x600 scale 1 pixels
|
||||||
|
root 0 0 800 116
|
||||||
|
enabled 2 2 796 20
|
||||||
|
volume 2 30 796 20
|
||||||
|
theme 2 58 796 24
|
||||||
|
port 2 90 796 24
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
surface thing:surface:provider.dialog.modal viewport 800x600 scale 1.5 pixels
|
||||||
|
root 0 0 1200 30
|
||||||
|
page-text 3 3 1194 24
|
||||||
|
overlay confirm-overlay anchor viewport
|
||||||
|
confirm-overlay 0 0 1200 900
|
||||||
|
dialog 0 399 1200 102
|
||||||
|
dialog-title 3 402 1194 24
|
||||||
|
confirm 3 438 1194 24
|
||||||
|
confirm-label 3 438 72 24
|
||||||
|
cancel 3 474 1194 24
|
||||||
|
cancel-label 3 474 72 24
|
||||||
11
crates/thing-core/tests/goldens/layout-f05-modal-overlay.txt
Normal file
11
crates/thing-core/tests/goldens/layout-f05-modal-overlay.txt
Normal file
|
|
@ -0,0 +1,11 @@
|
||||||
|
surface thing:surface:provider.dialog.modal viewport 800x600 scale 1 pixels
|
||||||
|
root 0 0 800 20
|
||||||
|
page-text 2 2 796 16
|
||||||
|
overlay confirm-overlay anchor viewport
|
||||||
|
confirm-overlay 0 0 800 600
|
||||||
|
dialog 0 266 800 68
|
||||||
|
dialog-title 2 268 796 16
|
||||||
|
confirm 2 292 796 16
|
||||||
|
confirm-label 2 292 48 16
|
||||||
|
cancel 2 316 796 16
|
||||||
|
cancel-label 2 316 48 16
|
||||||
2002
crates/thing-core/tests/goldens/layout-f06-scroll-list-scale1.5.txt
Normal file
2002
crates/thing-core/tests/goldens/layout-f06-scroll-list-scale1.5.txt
Normal file
File diff suppressed because it is too large
Load diff
2002
crates/thing-core/tests/goldens/layout-f06-scroll-list.txt
Normal file
2002
crates/thing-core/tests/goldens/layout-f06-scroll-list.txt
Normal file
File diff suppressed because it is too large
Load diff
5
crates/thing-core/tests/goldens/layout-f07-plot.txt
Normal file
5
crates/thing-core/tests/goldens/layout-f07-plot.txt
Normal file
|
|
@ -0,0 +1,5 @@
|
||||||
|
surface thing:surface:provider.market.plot viewport 800x600 scale 1 pixels
|
||||||
|
root 0 0 800 470
|
||||||
|
line 2 2 300 150
|
||||||
|
bar 2 160 300 150
|
||||||
|
area 2 318 300 150
|
||||||
|
|
@ -0,0 +1,5 @@
|
||||||
|
surface thing:surface:provider.viewport.embed-viewport viewport 800x600 scale 1.5 pixels
|
||||||
|
root 0 0 1200 276
|
||||||
|
before 3 3 72 270
|
||||||
|
viewport 366 3 480 270
|
||||||
|
after 1137 3 60 270
|
||||||
|
|
@ -0,0 +1,5 @@
|
||||||
|
surface thing:surface:provider.viewport.embed-viewport viewport 800x600 scale 1 pixels
|
||||||
|
root 0 0 800 184
|
||||||
|
before 2 2 48 180
|
||||||
|
viewport 244 2 320 180
|
||||||
|
after 758 2 40 180
|
||||||
|
|
@ -0,0 +1,14 @@
|
||||||
|
surface thing:surface:provider.stack.stack viewport 800x600 scale 1 pixels
|
||||||
|
root 0 0 800 168
|
||||||
|
std-stat 2 2 796 36
|
||||||
|
std-stat/stat-label 2 2 796 16
|
||||||
|
std-stat/stat-value 2 22 796 16
|
||||||
|
outer-card 2 46 796 120
|
||||||
|
outer-card/card-title 4 48 792 16
|
||||||
|
outer-card/card-act 4 72 792 16
|
||||||
|
outer-card/card-act-label 4 72 32 16
|
||||||
|
inner-card 4 96 792 68
|
||||||
|
inner-card/card-title 6 98 788 16
|
||||||
|
inner-card/card-act 6 122 788 16
|
||||||
|
inner-card/card-act-label 6 122 32 16
|
||||||
|
inner-note 6 146 788 16
|
||||||
8
crates/thing-core/tests/goldens/layout-f10-hostile.txt
Normal file
8
crates/thing-core/tests/goldens/layout-f10-hostile.txt
Normal file
|
|
@ -0,0 +1,8 @@
|
||||||
|
surface thing:surface:provider.hostile.duplicate-id refused DuplicateNodeId
|
||||||
|
surface thing:surface:provider.hostile.schema-mismatch viewport 800x600 scale 1 pixels
|
||||||
|
root 0 0 800 20
|
||||||
|
mismatch 2 2 796 16
|
||||||
|
surface thing:surface:provider.hostile.undeclared-command refused UndeclaredCommand
|
||||||
|
surface thing:surface:provider.hostile.unresolved-use viewport 800x600 scale 1 pixels
|
||||||
|
root 0 0 800 20
|
||||||
|
ghost-use 2 2 796 16
|
||||||
85
crates/thing-core/tests/goldens/layout-f11-deep.txt
Normal file
85
crates/thing-core/tests/goldens/layout-f11-deep.txt
Normal file
|
|
@ -0,0 +1,85 @@
|
||||||
|
surface thing:surface:provider.deep.deep viewport 800x600 scale 1 pixels
|
||||||
|
deep-0 0 0 800 336
|
||||||
|
deep-1 2 2 796 332
|
||||||
|
deep-2 4 4 792 328
|
||||||
|
deep-3 6 6 788 324
|
||||||
|
deep-4 8 8 784 320
|
||||||
|
deep-5 10 10 780 316
|
||||||
|
deep-6 12 12 776 312
|
||||||
|
deep-7 14 14 772 308
|
||||||
|
deep-8 16 16 768 304
|
||||||
|
deep-9 18 18 764 300
|
||||||
|
deep-10 20 20 760 296
|
||||||
|
deep-11 22 22 756 292
|
||||||
|
deep-12 24 24 752 288
|
||||||
|
deep-13 26 26 748 284
|
||||||
|
deep-14 28 28 744 280
|
||||||
|
deep-15 30 30 740 276
|
||||||
|
deep-16 32 32 736 272
|
||||||
|
deep-17 34 34 732 268
|
||||||
|
deep-18 36 36 728 264
|
||||||
|
deep-19 38 38 724 260
|
||||||
|
deep-20 40 40 720 256
|
||||||
|
deep-21 42 42 716 252
|
||||||
|
deep-22 44 44 712 248
|
||||||
|
deep-23 46 46 708 244
|
||||||
|
deep-24 48 48 704 240
|
||||||
|
deep-25 50 50 700 236
|
||||||
|
deep-26 52 52 696 232
|
||||||
|
deep-27 54 54 692 228
|
||||||
|
deep-28 56 56 688 224
|
||||||
|
deep-29 58 58 684 220
|
||||||
|
deep-30 60 60 680 216
|
||||||
|
deep-31 62 62 676 212
|
||||||
|
deep-32 64 64 672 208
|
||||||
|
deep-33 66 66 668 204
|
||||||
|
deep-34 68 68 664 200
|
||||||
|
deep-35 70 70 660 196
|
||||||
|
deep-36 72 72 656 192
|
||||||
|
deep-37 74 74 652 188
|
||||||
|
deep-38 76 76 648 184
|
||||||
|
deep-39 78 78 644 180
|
||||||
|
deep-40 80 80 640 176
|
||||||
|
deep-41 82 82 636 172
|
||||||
|
deep-42 84 84 632 168
|
||||||
|
deep-43 86 86 628 164
|
||||||
|
deep-44 88 88 624 160
|
||||||
|
deep-45 90 90 620 156
|
||||||
|
deep-46 92 92 616 152
|
||||||
|
deep-47 94 94 612 148
|
||||||
|
deep-48 96 96 608 144
|
||||||
|
deep-49 98 98 604 140
|
||||||
|
deep-50 100 100 600 136
|
||||||
|
deep-51 102 102 596 132
|
||||||
|
deep-52 104 104 592 128
|
||||||
|
deep-53 106 106 588 124
|
||||||
|
deep-54 108 108 584 120
|
||||||
|
deep-55 110 110 580 116
|
||||||
|
deep-56 112 112 576 112
|
||||||
|
deep-57 114 114 572 108
|
||||||
|
deep-58 116 116 568 104
|
||||||
|
deep-59 118 118 564 100
|
||||||
|
deep-60 120 120 560 96
|
||||||
|
deep-61 122 122 556 92
|
||||||
|
deep-62 124 124 552 88
|
||||||
|
deep-63 126 126 548 84
|
||||||
|
deep-64 128 128 544 80
|
||||||
|
deep-65 130 130 540 76
|
||||||
|
deep-66 132 132 536 72
|
||||||
|
deep-67 134 134 532 68
|
||||||
|
deep-68 136 136 528 64
|
||||||
|
deep-69 138 138 524 60
|
||||||
|
deep-70 140 140 520 56
|
||||||
|
deep-71 142 142 516 52
|
||||||
|
deep-72 144 144 512 48
|
||||||
|
deep-73 146 146 508 44
|
||||||
|
deep-74 148 148 504 40
|
||||||
|
deep-75 150 150 500 36
|
||||||
|
deep-76 152 152 496 32
|
||||||
|
deep-77 154 154 492 28
|
||||||
|
deep-78 156 156 488 24
|
||||||
|
deep-79 158 158 484 20
|
||||||
|
deep-80 160 160 480 16
|
||||||
|
deep-81 162 162 476 12
|
||||||
|
deep-82 164 164 472 8
|
||||||
|
deep-83 166 166 468 4
|
||||||
|
|
@ -0,0 +1,7 @@
|
||||||
|
surface thing:surface:provider.text.text-edge viewport 800x600 scale 1.5 pixels
|
||||||
|
root 0 0 1200 342
|
||||||
|
bidi 3 3 1194 24
|
||||||
|
cjk 3 39 1194 24
|
||||||
|
combining 3 75 1194 24
|
||||||
|
emoji-zwj 3 111 1194 24
|
||||||
|
long-wrap 3 147 1194 192
|
||||||
7
crates/thing-core/tests/goldens/layout-f12-text-edge.txt
Normal file
7
crates/thing-core/tests/goldens/layout-f12-text-edge.txt
Normal file
|
|
@ -0,0 +1,7 @@
|
||||||
|
surface thing:surface:provider.text.text-edge viewport 800x600 scale 1 pixels
|
||||||
|
root 0 0 800 228
|
||||||
|
bidi 2 2 796 16
|
||||||
|
cjk 2 26 796 16
|
||||||
|
combining 2 50 796 16
|
||||||
|
emoji-zwj 2 74 796 16
|
||||||
|
long-wrap 2 98 796 128
|
||||||
|
|
@ -0,0 +1,9 @@
|
||||||
|
surface thing:surface:provider.swarm.dashboard viewport 100x37 scale 1 cells
|
||||||
|
fill 0 0 100 6 r8 #1e1e2eff
|
||||||
|
text 0 0 #ffffffff cells "42.0%" bold=false italic=false underline=false
|
||||||
|
text 51 0 #eeeef4ff cells "Eureka" bold=false italic=false underline=false
|
||||||
|
text 0 2 #eeeef4ff cells "Libby" bold=false italic=false underline=false
|
||||||
|
text 51 2 #eeeef4ff cells "Kiko" bold=false italic=false underline=false
|
||||||
|
fill 0 3 50 3 r0 #2c2c3eff
|
||||||
|
stroke 0 3 50 3 r0 w1 #4a4a60ff
|
||||||
|
text 1 4 #eeeef4ff cells "Restart" bold=false italic=false underline=false
|
||||||
|
|
@ -0,0 +1,9 @@
|
||||||
|
surface thing:surface:provider.swarm.dashboard viewport 800x600 scale 1 pixels
|
||||||
|
fill 0 0 800 68 r8 #1e1e2eff
|
||||||
|
text 2 2 #ffffffff font0 size16 [52@0,0 50@8,0 46@16,0 48@24,0 37@32,0]
|
||||||
|
text 404 2 #eeeef4ff font0 size16 [69@0,0 117@8,0 114@16,0 101@24,0 107@32,0 97@40,0]
|
||||||
|
text 2 26 #eeeef4ff font0 size16 [76@0,0 105@8,0 98@16,0 98@24,0 121@32,0]
|
||||||
|
text 404 26 #eeeef4ff font0 size16 [75@0,0 105@8,0 107@16,0 111@24,0]
|
||||||
|
fill 2 50 398 16 r0 #2c2c3eff
|
||||||
|
stroke 2 50 398 16 r0 w1 #4a4a60ff
|
||||||
|
text 2 50 #eeeef4ff font0 size16 [82@0,0 101@8,0 115@16,0 116@24,0 97@32,0 114@40,0 116@48,0]
|
||||||
|
|
@ -0,0 +1,6 @@
|
||||||
|
surface thing:surface:provider.login.login viewport 800x600 scale 1 pixels
|
||||||
|
stroke 2 2 796 24 r0 w1 #4a4a60ff
|
||||||
|
text 4 4 #6e6e80ff font0 size16 [117@0,0 115@8,0 101@16,0 114@24,0 110@32,0 97@40,0 109@48,0 101@56,0]
|
||||||
|
fill 2 34 796 16 r0 #3a3a48ff
|
||||||
|
stroke 2 34 796 16 r0 w1 #4a4a60ff
|
||||||
|
text 2 34 #eeeef4ff font0 size16 [83@0,0 105@8,0 103@16,0 110@24,0 32@32,0 105@40,0 110@48,0]
|
||||||
|
|
@ -0,0 +1,6 @@
|
||||||
|
surface thing:surface:provider.login.login viewport 800x600 scale 1 pixels
|
||||||
|
stroke 2 2 796 24 r0 w1 #4a4a60ff
|
||||||
|
text 4 4 #6e6e80ff font0 size16 [117@0,0 115@8,0 101@16,0 114@24,0 110@32,0 97@40,0 109@48,0 101@56,0]
|
||||||
|
fill 2 34 796 16 r0 #2c2c3eff
|
||||||
|
stroke 2 34 796 16 r0 w1 #4a4a60ff
|
||||||
|
text 2 34 #eeeef4ff font0 size16 [83@0,0 105@8,0 103@16,0 110@24,0 32@32,0 105@40,0 110@48,0]
|
||||||
|
|
@ -0,0 +1,3 @@
|
||||||
|
surface thing:surface:provider.muninn.input-target viewport 800x600 scale 1 pixels
|
||||||
|
image 82 3.125 636 357.75 "asset://provider.muninn/board.png" "The board the target sits on"
|
||||||
|
text 282 122 #eeeef4ff font0 size16 [82@0,0 101@8,0 97@16,0 100@24,0 121@32,0]
|
||||||
|
|
@ -0,0 +1,9 @@
|
||||||
|
surface thing:surface:provider.settings.form viewport 800x600 scale 1 pixels
|
||||||
|
stroke 2 2 796 20 r0 w1 #4a4a60ff
|
||||||
|
fill 4 4 16 16 r0 #7c9cffff
|
||||||
|
fill 2 37.5 796 5 r0 #4a4a60ff
|
||||||
|
fill 196 30 20 20 r0 #7c9cffff
|
||||||
|
stroke 2 58 796 24 r0 w1 #4a4a60ff
|
||||||
|
text 4 60 #eeeef4ff font0 size16 [76@0,0 105@8,0 103@16,0 104@24,0 116@32,0]
|
||||||
|
stroke 2 90 796 24 r0 w1 #4a4a60ff
|
||||||
|
text 4 92 #eeeef4ff font0 size16 [57@0,0 57@8,0 57@16,0 57@24,0]
|
||||||
9
crates/thing-core/tests/goldens/render-f04-form.txt
Normal file
9
crates/thing-core/tests/goldens/render-f04-form.txt
Normal file
|
|
@ -0,0 +1,9 @@
|
||||||
|
surface thing:surface:provider.settings.form viewport 800x600 scale 1 pixels
|
||||||
|
stroke 2 2 796 20 r0 w1 #4a4a60ff
|
||||||
|
fill 780 4 16 16 r0 #7c9cffff
|
||||||
|
fill 2 37.5 796 5 r0 #4a4a60ff
|
||||||
|
fill 778 30 20 20 r0 #7c9cffff
|
||||||
|
stroke 2 58 796 24 r0 w1 #4a4a60ff
|
||||||
|
text 4 60 #eeeef4ff font0 size16 [68@0,0 97@8,0 114@16,0 107@24,0]
|
||||||
|
stroke 2 90 796 24 r0 w1 #4a4a60ff
|
||||||
|
text 4 92 #eeeef4ff font0 size16 [56@0,0 48@8,0 56@16,0 48@24,0]
|
||||||
|
|
@ -0,0 +1,11 @@
|
||||||
|
surface thing:surface:provider.dialog.modal viewport 800x600 scale 1.5 pixels
|
||||||
|
text 2 2 #eeeef4ff font0 size16 [84@0,0 104@8,0 101@16,0 32@24,0 97@32,0 114@40,0 99@48,0 104@56,0 105@64,0 118@72,0 101@80,0 32@88,0 104@96,0 111@104,0 108@112,0 100@120,0 115@128,0 32@136,0 49@144,0 50@152,0 32@160,0 105@168,0 116@176,0 101@184,0 109@192,0 115@200,0 46@208,0]
|
||||||
|
fill 0 0 800 600 r0 #00000099
|
||||||
|
fill 0 266 800 68 r6 #2c2c3eff
|
||||||
|
text 2 268 #eeeef4ff font0 size16 [68@0,0 101@8,0 108@16,0 101@24,0 116@32,0 101@40,0 32@48,0 116@56,0 104@64,0 101@72,0 32@80,0 97@88,0 114@96,0 99@104,0 104@112,0 105@120,0 118@128,0 101@136,0 63@144,0]
|
||||||
|
fill 2 292 796 16 r0 #2c2c3eff
|
||||||
|
stroke 2 292 796 16 r0 w1 #4a4a60ff
|
||||||
|
text 2 292 #eeeef4ff font0 size16 [68@0,0 101@8,0 108@16,0 101@24,0 116@32,0 101@40,0]
|
||||||
|
fill 2 316 796 16 r0 #2c2c3eff
|
||||||
|
stroke 2 316 796 16 r0 w1 #4a4a60ff
|
||||||
|
text 2 316 #eeeef4ff font0 size16 [67@0,0 97@8,0 110@16,0 99@24,0 101@32,0 108@40,0]
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue